如何在C ++中以附加模式清除文件 [英] How to clear a file in append mode in C++
问题描述
我有一个文件,需要对其进行多次操作.有时我只想在文件末尾附加数据,有时我只想从文件中读取数据,有时我想擦除所有数据并从文件的开头写入.然后,我再次需要在文件末尾附加数据.
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.
我正在使用以下代码:
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
但是我所做的无法正常工作.请给我建议一些C ++解决方案. (不在C中)
But what I've done doesn't work correctly. Please suggest me some solution in C++. ( Not in C)
推荐答案
代码存在的问题是:
在再次调用方法 open 之前,我没有关闭文件.
I wasn't closing the file before I called the method open again on it.
因此,在使用某些不同权限重新打开文件之前,请先close
文件.
So, close
the file before you re-open it with some different permissions.
这篇关于如何在C ++中以附加模式清除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!