将数据附加到 csv 文件,在最后一个条目之前而不是在最后一个条目之后。 C++

Appending data to csv file, before last entry instead of after last entry. C++

提出这个问题并不容易,所以对于任何悲伤,我深表歉意.. 我现在正在写这样的 csv 文件:

double indicators::SMACurrentWrite() {

if ( !boost::filesystem::exists( "./CalculatedOutput/SMAcurrent.csv" ) ) // std::cout << "Can't find my file!" << std::endl;
    {
        std::ofstream SMAfile;              
        SMAfile.open("./CalculatedOutput/SMAcurrent.csv");
        SMAfile << "SMA" << endl << SMA[0] << endl; // .. or with '\n' at the end.
        SMAfile.close();
    }
else    {   
        std::ofstream SMAfile;
        SMAfile.open ("./CalculatedOutput/SMAcurrent.csv", ios::app); // Append mode
    SMAfile << SMA[0] << endl; // Writing data to file
SMAfile.close();
}
return 0;
}

每次应用程序运行时,都会在输出文件末尾附加一个新值:

SMA
32.325

我想没有办法将新的向量条目压缩到 header(和数字之上),但这就是我想要完成的。 所以我想我必须重新读取现有的输出文件,将其放入向量中,然后替换旧文件?我是这样开始的:

double indicators::SMACurrentWrite() {

if ( !boost::filesystem::exists( "./CalculatedOutput/SMAcurrent.csv" ) ) // std::cout << "Can't find my file!" << std::endl;
    {
        std::ofstream SMAfile;              
        SMAfile.open("./CalculatedOutput/SMAcurrent.csv", ios::app);
        SMAfile << "SMA" << endl << SMA[0] << endl; // .. or with '\n' at the end.
        SMAfile.close();
    }
else    {   
        std::ofstream SMARfile("./CalculatedOutput/SMAReplacecurrent.csv");
        std::ifstream SMAfile("./CalculatedOutput/SMAcurrent.csv");

            SMARfile << SMA[0] << endl; // Writing data to file
        SMARfile << SMAfile.rdbuf();

        SMAfile.close();
        SMARfile.close();
        std::remove("./CalculatedOutput/SMAcurrent.csv");
            std::rename("./CalculatedOutput/SMAReplacecurrent.csv","./CalculatedOutput/SMAcurrent.csv");
}
return 0;
}

.....,但当然只是将新数据放在 header 之上,如下所示:

32.247
SMA
32.325

..而不是这个

SMA
32.247
32.325

我希望这不会变成如此耗时的练习,但我很感谢任何帮助我完成这项工作的人。

如果您从输入文件中读取第一行,您可以使用它来启动新文件,它将把文件指针留在旧数据开始的第二行。然后你可以这样写新的东西:

if(!boost::filesystem::exists("./CalculatedOutput/SMAcurrent.csv"))
{
    std::ofstream SMAfile;
    SMAfile.open("./CalculatedOutput/SMAcurrent.csv", ios::app);
    SMAfile << "SMA" << '\n' << SMA[0] << '\n';
    SMAfile.close();
}
else
{
    std::ofstream SMARfile("./CalculatedOutput/SMAReplacecurrent.csv");
    std::ifstream SMAfile("./CalculatedOutput/SMAcurrent.csv");

    // first read header from input file

    std::string header;
    std::getline(SMAfile, header);

    // Next write out the header followed by the new data
    // then everything else

    SMARfile << header << '\n';  // Writing header
    SMARfile << SMA[0] << '\n';  // Write new data after header
    SMARfile << SMAfile.rdbuf(); // Write rest of data

    SMAfile.close();
    SMARfile.close();
    std::remove("./CalculatedOutput/SMAcurrent.csv");
    std::rename("./CalculatedOutput/SMAReplacecurrent.csv",
        "./CalculatedOutput/SMAcurrent.csv");
}