Reputation: 23
I have a school project. The project requires me to write a function called openFiles. So I need to open a file inside the function and use it in main or other functions. How can I do that? Assumed my file is named "1"
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void openFiles(string);
main() {
openFiles("1");
string str;
while(file>>str)cout<<str;
}
void openFiles(string str){
fstream file;
file.open(str);
}
Upvotes: 2
Views: 128
Reputation: 25408
Because fstream
has a move constructor, you can return your fstream
object as the result of openFiles
, like so:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
fstream openFiles(string);
int main() {
auto file = openFiles("1");
string str;
while(file>>str)cout<<str;
}
fstream openFiles(string str){
fstream file;
file.open(str);
return file;
}
Of course, you should check if the open succeeds.
Upvotes: 4