【发布时间】:2014-01-12 05:21:48
【问题描述】:
我有一个需要多次操作的文件。有时我只想在文件末尾追加数据,有时我只想从文件中读取,有时我想擦除所有数据并从文件开头写入。然后,我再次需要在文件末尾附加数据。
我正在使用以下代码:
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 中)
【问题讨论】:
-
在再次调用 open 之前,您是否要关闭
writeToTempFile?您将需要这样做,否则打开失败。 cplusplus.com/reference/fstream/fstream/open "如果流已经与文件关联(即,它已经打开),则调用此函数失败。"
标签: c++ file file-handling