Passing fstream object to function
Hello.
I want my function to take 'fstream' object as an input, so the program looks like this:
Code:
#include <fstream>
using namespace std;
void test(fstream a){
a.open("test2.txt");
a << "123" << endl;
a.close();
}
int main(){
fstream a;
test(a);
return 0;
}
But I get the following error: 'std::ios_base::ios_base(const std::ios_base&)' is private|
Please help to make it work.
Re: Passing fstream object to function
Code:
#include <fstream>
using namespace std;
void test(fstream& a){
a.open("test2.txt");
a << "123" << endl;
a.close();
}
int main(){
fstream a;
test(a);
return 0;
}
pass fstream by ref rather than value. You can't pass a stream by value.
Re: Passing fstream object to function
Thanks, it can be compiled now, but expected .txt file is not created. Where is a catch?
Never mind. It must be written ofstream. Thanks again.
Re: Passing fstream object to function
Quote:
Originally Posted by
ted_kingdom
Thanks, it can be compiled now, but expected .txt file is not created. Where is a catch?
Never mind. It must be written ofstream. Thanks again.
There is no catch. You are trying to open test2.txt. If the file does not exist, then the file is not created but an error occurs. You are not checking that the file opens successfully before writing to it.
Code:
void test(fstream& a){
a.open("test2.txt");
if (a.is_open()) {
a << "123" << endl;
a.close();
} else {
cout << "Cannot open test2.txt\n";
}
}
If you always want the file to be created if it does not exist, then use
Code:
a.open("test2.txt", fstream::out);
Note that in both cases, the existing contents (if any) of the file will be overwriten.