I am trying to add a comma to the end of each line ('\n') of a text file til the end of the file is reached. I am opening the file in append mode but am unsure as to how to go about identifying when the end of line is reached and how to add the comma (perhaps replace the newline char with the comma).

Any suggestions?

3 Years
Discussion Span
Last Post by Jorox03

It's hard to modify the file itself character by character.

Read in the original line by line. Add the commas to the end of the lines (which you will have stored in a buffer) then write out the new line.

You write the new lines a temporary file then delete the original and rename the temporary file with the name of the original file.


Well, if the file is not that big, you could use a buffer (stringstream). Here's a small example:

#include <fstream>
#include <string>
#include <sstream>

int main(){
    std::string filename = "a.txt", line;
    std::ifstream fin(filename.c_str(), std::ios::in);
    if (fin.good()){                                         //check if the file exists and can be read
        std::stringstream bufer;                             //buffer to store the lines
        while (getline(fin, line)) bufer<<line+",\n";        //add comma
        std::ofstream fout(filename.c_str(), std::ios::out); //ofstream buffer
        fout<<bufer.rdbuf();                                 //write to file
    return 0;

Note, that this will replace your old file.
If your file is quite big, I suggest parsing it line by line, and in another file (at the same time), to write that line, with the ",\n" apendix.

Edited by Lucaci Andrew

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.