此程序在每次循环迭代时将一行数据写入三个文件一次。看着文件大小增加,我注意到它们并不是同时增长的。通常两个文件增长,一个保持接近零字节直到结束。为什么是这样?我假设正在进行某种优化;硬盘驱动器完成两个文件的写入比多个文件更容易完成吗?
#include <fstream>
#include <iostream>
#include <stdlib.h>//for rand and srand
#include <time.h>//for time()
using namespace std;
int main()
{
srand(time(NULL));
ofstream a1("f:\\test\\first.txt");
ofstream b1("f:\\test\\second.txt");
ofstream c1("f:\\test\\third.txt");
if(!a1 || !b1 || !c1)
{
cerr << "Cannot open the output files." << endl;
return 1;
}
cout << "Program has started:" << endl;
for(int i = 0; i < 50000000; i++)
{
a1<<rand() % 1000000 + 1;
a1<<"adsfgijasdflhkzxoijasdd";
a1<<"\n";
b1<<rand() % 1000000 + 1;
b1<<"kjhkjhkjhkhftfzxdtdtdliu";
b1<<"\n";
c1<<rand() % 1000000 + 1;
c1<<"kjlkjoijsegoihsdfoinsvfglkjhw";
c1<<"\n";
}
a1.close();
b1.close();
c1.close();
return 0;
}
我正在写入外部硬盘驱动器并使用 Windows 7。
最佳答案
简单的答案是,你的文件被缓冲到内存中,直到内核(在你的例子中是 Windows)决定它没有更好的事情要做并将缓冲区传递给驱动程序。
这可以通过调用 flush
来解决,这将 sync
缓冲区和文件,实际上,告诉内核立即写入它。
您还可以通过调用 setbuf(0,0)
告诉 ofstream
不使用缓冲区。这会将所有数据逐字节直接发送到文件中。它会大大降低您的程序速度,并且仅在文件一次打开多次时才有用。
关于c++ - 为什么在第三个文件之前写入两个文件,即使指令是每次迭代都执行一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17842425/