使用fstream打开文件后如何清除文件内容? [英] How to clear the content of a file after it is opened using fstream?

查看:2330
本文介绍了使用fstream打开文件后如何清除文件内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以读写模式打开文件,读取文件内容,然后清除所有文件。因此,我无法在截断模式下打开它。我该怎么办?

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打开文件后如何清除文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆