To write to the file rather than reading from it, you basically need to change the type of file
to an output stream (ofstream
), file
to cin
and cout
to file
. You can also simplify a few things. A stream will automatically convert to a true value if the next operation will succeed, and a false one if it will fail, so you can test a stream simply by referring to it. There's nothing wrong with (e.g.) while (file.good())
, it's just not as idiomatic as while (file)
.
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>
using namespace std;
int main () {
string line;
string fname="TEXT";
/* You can open a file when you declare an ofstream. The path
must be specified as a char* and not a string.[1]
*/
ofstream fout(fname.c_str(), ios::app);
// equivalent to "if (!fout.fail())"
if (fout) {
while (cin) {
getline(cin,line);
fout << line << endl;
}
fout.close();
} else {
/* Note: errno won't necessarily hold the file open failure cause
under some compilers [2], but there isn't a more standard way
of getting the reason for failure.
*/
cout << "Unable to open file \"" << fname << "\": " << strerror(errno);
}
}
References:
- Why don't the std::fstream classes take a std::string?
- Get std::fstream failure error messages and/or exceptions