加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何保存并读取c fstream文件而不关闭它

发布时间:2020-12-16 09:22:15 所属栏目:百科 来源:网络整理
导读:我打开了一个文件读写模式 使用以下语句 file.open(fileName,ios::in | ios::out | ios::trunc); 我在两种模式下打开文件的主要目的是同时读取和写入文件. 但在我的代码场景中, 当我在写完文件后读取文件时,输出显示空白意味着, 它没有保存我的写作内容,因为
我打开了一个文件读写模式

使用以下语句

file.open(fileName,ios::in | ios::out | ios::trunc);

我在两种模式下打开文件的主要目的是同时读取和写入文件.

但在我的代码场景中,

当我在写完文件后读取文件时,输出显示空白意味着,
它没有保存我的写作内容,因为我没有关闭它.

我想在完成写入和读取操作后关闭文件

我在Stack Overflow中找到了一个解决方案,

使用flush()函数保存文件而不关闭

file.flush();

但是,问题是它不适合我的情况

那么,如何在不关闭的情况下保存c fstream文件呢?

这是我完整的代码,以便更好地理解

#include <iostream>
#include <string>
#include <fstream>
using namespace std;


int main(int argc,char const *argv[])
{
    string fileName = "text.txt";

    fstream file;


    file.open(fileName,ios::in | ios::out | ios::trunc);

    if (file.is_open())
    {
        file << "I am a Programmer" << endl;
        file << "I love to play" << endl;
        file << "I love to work game and software development" << endl;
        file << "My id is: " << 1510176113 << endl;

        file.flush(); // not working 
    }
    else
    {
        cout << "can not open the file: " << fileName << endl;
    }

    if (file.is_open())
    {
        string line;

        while(file)
        {
            getline(file,line);

            cout << line << endl;
        }
    }
    else
    {
        cout << "can not read file: " << fileName << endl;
    }

    file.close();

    return 0;
}

解决方法

实际上,如果你想立即保存任何文件而不关闭文件,那么你可以简单地使用

file.flush();

但是,如果您想在不写入文件后立即阅读该文件,则可以直接使用

file.seekg(0);

实际上seekg()函数在开头重置文件指针,为此,不必保存文件.所以,这与flush()函数没什么关系

但如果你愿意,你可以做到

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读