我打开了一个文件读写模式 使用以下语句 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()函数没什么关系
但如果你愿意,你可以做到
