Home > Net >  File not updating
File not updating

Time:11-29

I am trying to read and write to a file. My file contains just one line that has a value. enter image description here

and this is my code where I am trying to calculate a mean value and write it in the file instead of the first one, but the file keeps containing 37.

long int moy;
std::string line;
std::fstream file;
long int x = 35   ( std::rand() % ( 37 - 35   1 ) );
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::out | std::ios::in);
std::getline(file, line);
std::cout<<line<<endl;
moy=(x stoi(line))/2;
file<<moy<<endl;
file.close();

The x variable contains different value every time, I also tried to write a string directly: file<<"test"<<endl; but still not updating.

CodePudding user response:

The simple way is to close the file before reopening it for writing.

file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::in);
std::getline(file, line);
file.close();
std::cout<<line<<endl;
moy=(x stoi(line))/2;
file.open ("C:/Users/MSI/Desktop/omnetpp-6.0.1/samples/inet4/src/inet/applications/udpapp/B1.txt", std::ios::out);
file<<moy<<endl;
file.close();

If you don't want to do that then you need to clear any error, and then reposition the file to the beginning.

file.clear(); // clear any error
file.seekp(0); // position file at beginning

The problem with this method is that it will not replace existing content. If your new line is shorter than the old line then the trailing characters of the old line will remain.

  • Related