在最后一次输入之前而不是最后一次输入之后,将数据追加到csv文件。 C++
问题描述:
不容易制定这个问题,所以我对任何的悲伤有抱歉.. 我此刻写入csv文件是这样的:在最后一次输入之前而不是最后一次输入之后,将数据追加到csv文件。 C++
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
我想是没有的只是挤了头(及以上数)下有新的载体进入的方式,但是这是我想要完成的任务无论如何。 所以我想我将不得不读取现有的输出文件,将其放入一个矢量,然后替换旧文件?我开始与水木清华这样的:比这个
32.247
SMA
32.325
..rather:
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;
}
...,但当然,这只是把新的数据在这样的头以上的
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");
}
+0
我标记你的答案是有用的,但因为它与Sam Varshavchik上面评论的完全相同的程序,所以我不确定我应该将它标记为答案。 。无论如何,我已经使用getline很多次了,但是......哈哈:-) – PushT
究竟是什么,你不能确定:1)读从现有的文件标题行,并将其写入新文件,2)写你的新行文件,以及3)读取原始文件的其余部分并将其写入新文件。看起来你已经完成了所有这些,95%的工作已经完成。在SMARfile
为什么不每次都从头开始重新创建文件*将旧内容读入内存,根据需要修改内存中的副本,全部写入新文件,将旧文件重命名(不需要除去)新文件。 –
是的,确实很多工作都完成了。谢谢你的反馈。我不得不把它归结为缺乏睡眠... – PushT