문제

I've a file on which I require multiple operations. Sometimes I just want to append data at the end of the file, sometimes I just want to read from the file, and sometimes, I want to erase all the data and write form the beginning of the file. And then, I again need to append data at the end of file.

I'm using following code:

ofstream writeToTempFile;
ifstream readFromTempFile;

writeToTempFile.open("tempFile.txt", ios::app | ios::out);
readFromTempFile.open("tempFile.txt", ios::in); 

// Reading and Appending data to the file
// Now it is time to erase all the previous data and start writing from the beginning


writeToTempFile.open("tempFile.txt", std::ofstream::trunc); // Here I'm removing the contents.

// Write some data to the file

writeToTempFile.open("tempFile.txt", std::ofstream::app); // Using this, I'm again having my file in append mode

But what I've done doesn't work correctly. Please suggest me some solution in C++. ( Not in C)

도움이 되었습니까?

해결책

The problem with the code is:

I wasn't closing the file before I called the method open again on it.

So, close the file before you re-open it with some different permissions.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top