I've 3 columns that change at each iteration (clock cycle). I want to store each value of those columns in a csv file. The csv file is Positions.csv. SUppose the variable I want to store are in: columnA, columnB and columnC variables. My file will be empty, at each cycle it will be filled with the columnA,columnB and columnC values. My following code doesn't work, In output file I've just one row.
I want to append at the end of the file columnA,columnB an columnC. I receive different values for those variable at each cycle.
I need a way to append row in a csv file.
double columnA , columnB, columnC;
// LOG START
std::ofstream coordscsv;
std::string filename = "Positions.csv";
coordscsv.open(filename);
//**************
std::ifstream data("Positions.csv");
std::string line;
while (std::getline(data, line))
{
std::stringstream lineStream(line);
std::string cell;
while (std::getline(lineStream, cell, ','))
{
coordscsv << cell;
}
}
coordscsv << columnA << ", " << columnB << ", " << columnC << "\n";
coordscsv.close();
CodePudding user response:
The default argument to ifstream
s constructor is ios_base::in
. To append to a file you want ios_base::app
.
However, you shouldn't open and close the file in every iteration anyhow. Open it once and unless you want to diagnose errors on closing it you don't need to call close()
explicitly (the destructor does that already).
CodePudding user response:
I solved with
coordscsv.open(filename, std::ios::app);
but now I want put a limit in file dimension. Any suggestion?