【问题标题】:How to clear a file in append mode in C++如何在 C++ 中以附加模式清除文件
【发布时间】: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


【解决方案1】:

代码的问题是:

在再次调用 open 方法之前,我并没有关闭文件。

所以,close 使用一些不同的权限重新打开文件之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多