How to clear a file in append mode in C++

淺唱寂寞╮ 提交于 2019-12-11 12:56:26

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/21071601/how-to-clear-a-file-in-append-mode-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!