我以读写模式打开文件
使用以下语句
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;
}
答案 0 :(得分:5)
实际上,如果要立即保存任何文件而不关闭文件,则只需使用
file.flush();
但是,如果您想在写入文件后不关闭文件的情况下读取文件,则只需使用
file.seekg(0);
实际上, seekg()函数会在开始时重置文件指针,为此,并非必须保存文件。因此,与flush()函数无关。
但如果您愿意,您可以同时做
答案 1 :(得分:2)
在从该文件读取之前,您需要确保将指向该文件的指针放在文件的开头。写入文件后,它将指向结尾。因此,您将无法阅读任何内容。
您需要在file.seekg(0);
之后但在开始读取之前的某个地方使用file.flush()
,以将文件指针放在最前面。
此应该无需冲洗即可。但是,这将取决于std库的实现。尽管我认为如果不调用flush()
imho无法正常工作,则将其视为错误,但是明确调用它不会有任何伤害。