Pergunta

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)

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top