0

该程序每次循环迭代一次将一行数据写入三个文件。看着文件大小增加,我注意到它们并没有同时增长。通常两个文件增长,一个保持接近零字节直到结束。为什么是这样?我假设正在进行某种优化;硬盘驱动器完成两个文件的写入比更多文件更容易吗?

#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。

4

1 回答 1

1

The simple answer is, your files are buffered into memory until the kernel (Windows in your case) decides it has nothing better to do and passes the buffer through to the driver.

This can be overcome by calling flush which will sync the buffer and the file, in effect, telling the kernel to write it straight away.

You can also tell ofstream to not use a buffer by calling setbuf(0,0). This will send all data directly to the file byte by byte. It will slow your program down considerably, and is only useful when the file is opened more than once at a time.

于 2013-07-24T19:48:14.780 回答