C++/Writing to a file
Expert: Zlatko - 3/12/2011
QuestionI am trying to convert a code which runs on windows to run on linux. Part of the code takes a string and writes it to a file. In windows I do this using this bit of code:
file.open ("Highscore.txt", fstream::in | fstream::out | fstream::app);
file.write(test,500);
file.close();
however this doesn't create or link to a file in linux. Is there another way to do this that will work in linux.
AnswerSam, I don't think this is a Linux issue. If the file does not already exist, then the only way file.open will succeed with fstream::in, is if you specify fstream::out and fstream::truc as well. However, I suspect that you do not want to trunc an existing file, so I suggest doing the open in 2 attempts, first with
in | out | ate, and if that fails, because the file doesn't exist, then use in | out | trunc.
If the file exists, the in | out | ate mode will succeed, and the file pointer will be set to the end of the file for appending. Here is sample code. I hope it helps.
Best regards
Zlatko
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
fstream file;
// Notice I am using fstream::ate here, not fstream::app
file.open("test.txt", fstream::in | fstream::out | fstream::ate);
if ( ! file.good())
{
file.clear(); // It is important to clear the error before the next operation
file.open("asd.txt", fstream::in | fstream::out | fstream::trunc);
if ( ! file.good())
{
cerr << "Cannot open file\n";
}
else
{
cerr << "Open file OK\n";
}
}
}