如何写回刚刚读过的csv文件(c ++)?

时间:2013-08-06 18:35:03

标签: c++ csv

我试图回写以前在程序中读取的csv文件。该计划目前看起来像这样:

ifstream file;

    file.open ("file");

    e=0;

    while (file.good()) {

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var1[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var2[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var3[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var4[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var5[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var6[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var7[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var8[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var9[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var10[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var11[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var12[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var13[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var14[e]=infoc;

        getline ( file, infor,',');
        istringstream (infor) >> infoc;
        var15[e]=infoc;

        ++e;

    }



    var1[e] = var1[e] + v1;
    var2[e] = var2[e] + v2;
    var3[e] = var3[e] + v3;
    var4[e] = var4[e] + v4;
    var5[e] = var5[e] + v5;
    var6[e] = var6[e] + v6;
    var7[e] = var7[e] + v7;
    var8[e] = var8[e] + v8;
    var9[e] = var9[e] + v9;
    var10[e] = var10[e] + v10;
    var11[e] = var11[e] + v11;
    var12[e] = var12[e] + v12;
    var13[e] = var13[e] + v13;
    var14[e] = var14[e] + v14;
    var15[e] = var15[e] + v15;
    //WRITE TO compYTD

    file.close();

在关闭文件之前,我想将新计算的变量写回文件,删除之前读取的所有内容。是否有允许我这样做的功能?还有一个单独的函数,允许我写回这个文件,添加到已经存在的行?

1 个答案:

答案 0 :(得分:0)

我个人会关闭该文件,然后使用以下内容编写新值:

ofstream ofile("file.csv"); 

for(int i = 0; i < e; i++)
   ofile << var1[i] << ", " << var2[i] << ", " << var3[i] << ", " << ... endl;

ofile.close();

(当然,如果var1var2等在一个数组或一个向量中会更容易 - 当然在读取它时也是如此 - 只是{{1}的一个实例1}},getline等。)

要在文件中附加(添加信息),您可以使用istringstream作为ios_base::app的标记。再次,您关闭输入文件,并在ofstream

中打开输出
ofstream

您写入文件的任何内容现在都位于文件的末尾。