我需要以读写模式打开文件,读取文件内容,然后清除所有文件。因此,我无法在截断模式下打开它。我该怎么办?
I need to open a file in read/write mode, read its content and then clear all. So, I cannot open it in truncate mode. How can I do that?
推荐答案讨厌让你失望,但是..
没有从打开的 std :: fstream 清除文件内容的标准方法,因此直接的方法是按实际的方式处理这两个操作。 two 操作。
Hate to disappoint you, but..
There's no standard way of clearing the contents of a file from an open std::fstream, the straight forward way is therefore to handle the two operations as what they really are.. two operations.
首先处理所有读取,然后处理写入(通过不同的 stream对象)。
First handle all the reading, and later the writing (through a different stream object).
首先以只读模式( std :: ifstream )打开文件并读取您感兴趣的数据,然后丢弃该文件句柄并再次打开文件。 。这次是在只写和截断模式( std :: ofstream )下进行的操作,以便清除文件内容。 / p>
In other words; first open the file in read-only mode (std::ifstream) and read the data you are interested in, then discard that file-handle and open the file again.. this time in write-only and truncation mode (std::ofstream), so that you will clear the contents of the file.
std::ifstream ifs ("some_file.txt"); ... // read old data ifs.close (); std::ofstream ofs ("some_file.txt", std::ios::out | std::ios::trunc); // clear contents ... // write new data ofs.close ();更多推荐
使用fstream打开文件后如何清除文件内容?
发布评论