【发布时间】:2017-11-20 02:43:43
【问题描述】:
为什么在一个文件上写入多个 ostream 以产生不同的输出顺序?例如:
#include <iostream>
#include <fstream>
using namespace std;
void writeTo(string filename){
ostream o;
o.open(filename, ios::app);
o << "Second\n";
o.close();
}
int main(){
ostream o;
o.open("foo.txt", ios::app);
o << "First\n";
writeTo("foo.txt");
o.close();
return 0;
}
输出文件是
Second
First
为什么会这样?不应该是第一然后第二吗?
我知道我可以通过拥有一个流并通过引用传递它来实现此行为,但我很困惑是什么导致了同一文件上的多个流的这种行为:
#include <iostream>
#include <fstream>
using namespace std;
void writeTo(ostream& o){
o << "Second\n";
}
int main(){
ostream o;
o.open("foo.txt", ios::app);
o << "First\n";
writeTo(o);
o.close();
return 0;
}
【问题讨论】:
-
函数内部的
ostream在main()之前被销毁,所以它首先刷新它的缓冲区。 -
@cantordust 有意思,你能引用一下吗?
-
您正在显式调用
close(),因此从技术上讲,缓冲区在流被销毁之前被刷新,但这无关紧要,因为析构函数无论如何都会调用close()。见here:[...] first calls overflow(Traits::eof()) to write all pending output to the file [...]。如果你调用o.close()之前在main()中调用writeTo("foo.txt");,你应该得到First后跟Second。