使用fstream打开文件后如何清除文件内容?

编程入门 行业动态 更新时间:2024-10-23 14:22:52
本文介绍了使用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打开文件后如何清除文件内容?

本文发布于:2023-11-03 16:23:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   内容   fstream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!