0

I would like to append entries in a simple csv file at the second line. The first line contains my column headers and the newest entry has to be on top.
My thought is to read in the first line until the '\n', then move to the next line and write there, but i don't know if that is the most efficient solution. Can someone provide an example?

Jason
  • 2,147
  • 6
  • 32
  • 40
  • 1
    I had that coming. Editing to actually be a useful question. – Jason Aug 27 '15 at 17:27
  • I would look at this question http://stackoverflow.com/questions/9033060/c-function-to-insert-text-at-particular-location-in-file-without-over-writing-th – rkh Aug 27 '15 at 17:29
  • 1
    How big is this file expected to get? If this is some sort of log they typically grow at the end as that is a much more efficient operation. – NathanOliver Aug 27 '15 at 17:34
  • Likely no more than 64 char/line and no more than 30 entries. – Jason Aug 27 '15 at 17:35
  • It might make much more sense to append at the end, rather than keep shuffling the older data down and provide a view that just shows the tail of the file. – doctorlove Aug 27 '15 at 17:36

1 Answers1

1

Since you have stated in the comments that this file will not be very large I would suggest you read in the header into some sort of container. Then insert after the header the newest data that needs to be inserted into the file. Then read in the rest of the file. After you do that then you can write the contents of the container back into the file. Here is a simple demonstration:

std::ifstream fin("somefilename");
std::vector<std::string> file;
file.reserve(30); // grow the capacity to save on allocations
std::string reader;

std::string new_data = "some new data";
getline(fin, reader);
file.push_back(reader);  //add header
file.push_back(new_data);  // add new line

while(getline(fin, reader))  // get rest of file
    file.push_back(reader);

std::ofstream fout("somefilename");
for (const auto & e : file)
    fout << e << "\n";
NathanOliver
  • 171,901
  • 28
  • 288
  • 402