如何在使用fstream打开一个文件后清除其内容? 您所在的位置:网站首页 fstream清空文件内容 如何在使用fstream打开一个文件后清除其内容?

如何在使用fstream打开一个文件后清除其内容?

2024-04-13 20:32| 来源: 网络整理| 查看: 265

百度翻译此文   有道翻译此文 问题描述

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?

推荐答案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.

First handle all the reading, and later the writing (through a different stream object).

The solution

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 (); 其他推荐答案

You could just rename the file before reading it and create an empty file with the original name.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有