I’m trying to write a long to a text file using c++ fstream class. The file is already created on disk before the execution. I run the following code and can read the initial value but can’t save the new one, overwriting. What am i doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
long f;
fstream myFile("data.txt", fstream::in|fstream::out);
cout << "f before: " << f << endl;
myFile >> f;
cout << "f after: " << f << endl;
f++;
cout << "f after increment: " << f << endl;
myFile << f;
myFile.close();
return 0;
}
After that, I read the value in the file and it isn’t changed. What I did wrong here?
You need to add
myFile.seekp(ios::beg);just beforemyFile << f;in order to update the count correctly.If you want to keep appending to the end, add
myFile.clear();beforemyFile << f;. This will cause the contents to become :1->12->1213->12131214->1213121412131215. This is required because eof is reached upon reading the input. Note that get and put pointers are the same.As you have yourself correctly pointed out, this is required because the file has just the number, not even the newline. Thus the read operation hits straight the EOF and causes problems. To work around it, we clear eof status and continue.
Adding a newline at the end is a solution as you suggested. In that case
Would be the complete solution.