编写文件c ++的性能

Car*_*rme 1 c++ performance writefile

我需要用c ++编写一个文件.内容是来自while循环的标记,所以现在我逐行编写它.现在我想我可以改善写入时间,保存变量中的所有内容然后写入文件.有人知道这两种方式中的哪一种更好?

每行都由此函数写入:

void writeFile(char* filename, string value){
        ofstream outFile(filename, ios::app);
        outFile << value;
        outFile.close();
}

while(/*    Something   */){
   /*   something   */
   writeFile(..);

}
Run Code Online (Sandbox Code Playgroud)

另一种方式是:

void writeNewFile(char* filename, string value){
    ofstream outFile(filename);
    outFile<<value;
    outFile.close();
}

string res = "";
while(/*    Something   */){
   /*   something   */
   res += mydata;

}
writeNewFile(filename, res);
Run Code Online (Sandbox Code Playgroud)

Sor*_*ren 7

你有没有考虑过;

ofstream outFile(filename);
while(/*    Something   */){
   /*...*/    
   outFile<< mydata;
}
outFile.close();
Run Code Online (Sandbox Code Playgroud)

outfile(流)是缓冲的,这意味着它会在将数据写入磁盘之前将数据累积在内部缓冲区(如字符串)中 - 除非你有非常特殊的要求,否则你不太可能打败它