【问题标题】:using stringstream and ofstream to write long log file使用 stringstream 和 ofstream 写长日志文件
【发布时间】:2013-07-12 17:14:12
【问题描述】:

我需要将变量的值写入持久文件。每个写入操作都应该在同一个文件中添加一个新行,并且该文件最终将包含来自数百万个写入操作的数百万行数据。我在下面写的代码确实写入了文件,但问题是它一次又一次地覆盖了同一行。另外,我不确定我是否正确地转义了行尾,因为它还没有输出多行。谁能告诉我如何修改下面的代码,使其写入尽可能多的数据行?

#include <sstream>  
#include <string>  

void writeToFile(std::stringstream& ss){  
    using namespace std;  
    string myString = ss.str();  
    ofstream myfile;  
    myfile.open ("somefile.txt");  
    myfile << myString;  
    myfile.close();  
}  

void anotherFunction(){    
    using namespace std;
    stringstream mySS;
    mySS << someVar; mySS << ", "; mySS << var2;
    mySS << ", "; mySS << something; mySS << ", "; mySS << somethingelse; mySS << ", ";
    mySS << dayofweek; mySS << ", "; mySS << time; mySS << ", ";
    mySS << whichbone; mySS << ", "; mySS << name; mySS << "\n" << endl;
    writeToFile(mySS);
}

void aThirdFunction(){
    using namespace std;    
    stringstream mySS;    
    mySS << someVar; mySS << ", "; mySS << var2;    
    mySS << ", "; mySS << var3; mySS << ", "; mySS << fourthVar; mySS << ", ";    
    mySS << fifthVar; mySS << ", "; mySS << sixthVar; mySS << "\n" << endl;    
    writeToFile(mySS);    
}    

【问题讨论】:

    标签: c++ csv io


    【解决方案1】:

    您需要打开输出文件进行追加:myfile.open ("somefile.txt", ios_base::app);
    否则每次重新打开时它都会被截断为 0。

    【讨论】:

    • +1 并感谢您一针见血的答案。这现在有效。令人印象深刻的响应时间。您的答案唯一不包括的是“\n”变得多余,并且在添加修复后添加了一个空行。
    猜你喜欢
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2019-02-24
    相关资源
    最近更新 更多