[英]Update ifstream object after data is written to its file using ofstream
While testing my code, I faced an issue, that ifstream
doesn't get updated when more data is written to its file. 在测试代码时,我遇到一个问题,即当有更多数据写入其文件时, ifstream
不会得到更新。 So here is a sample code that demonstrates the problem: 因此,以下是示例代码演示了此问题:
ifstream is(filename);
string line;
while (getline(is, line))
cout << "line: " << line << endl;
ofstream os(filename, ofstream::out | ofstream::app);
string additional("additional");
os << additional;
os.flush();
while (getline(is, line))
cout << "line additional: " << line << endl;
No additional lines were written to stdout
, though they are written to the file. 尽管其他行已写入文件, stdout
其他行写入stdout
。 I'm not using fstream
instead of a couple of if/ofstream because I need it like this for testing purposes. 我没有使用fstream
而不是几个if / ofstream,因为出于测试目的,我需要像这样使用它。
How to make ifstream
"see" the changes in the file? 如何使ifstream
“查看”文件中的更改?
UPDATE : I cleared the bits using clear
method. 更新 :我使用clear
方法清除了位。 It works OK on my Ubuntu machine with gcc. 它可以在我的带有gcc的Ubuntu计算机上正常运行。 But it doesn't work on my Mac OSX with llvm. 但是在带有llvm的Mac OSX上它不起作用。 Do you know how to do it platform independently? 你知道如何独立地做它吗?
You need to call std::ios::clear
on the input stream after the first read. 第一次读取后,您需要在输入流上调用std::ios::clear
。 When you read the whole file, it sets the failbit in the stream and will refuse to keep reading, even if the file actually changed in the meantime. 当您读取整个文件时,即使在此期间实际更改了文件,它也会在流中设置故障位,并且将拒绝继续读取。
ifstream is(filename);
string line;
while (getline(is, line))
cout << "line: " << line << endl;
ofstream os(filename, ofstream::out | ofstream::app);
string additional("additional");
os << additional;
os.flush();
is.clear(); //< Now we can read again
while (getline(is, line))
cout << "line additional: " << line << endl;
When you hit the end of the file while reading is
the first time, it sets the eofbit
in the stream's internal error state. 当你点击文件的末尾,而阅读is
第一次,这台eofbit
在流的内部错误状态。
You need to clear it before you can continuing reading, by calling the is.clear()
function, which resets the internal error state. 您需要通过调用is.clear()
函数来清除它,然后才能继续阅读,该函数将重置内部错误状态。
I think the reason is that you have opened output stream file using "ofstream::out" 我认为原因是您使用“ ofstream :: out”打开了输出流文件
ofstream os(filename, ofstream::out | ofstream::app);
now, the "ofstream::out" truncates the file as soon as it opens it. 现在,“ ofstream :: out”一旦打开文件就会将其截断。 That is, all the previous contents of your file will be deleted once it is opened. 也就是说,文件的所有先前内容一旦打开就将被删除。 Please try using this instead: 请尝试使用此代替:
ofstream os(filename, ios::app);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.