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?

Dani AI

Generated

Good call not trying to do this in-place. Appending with ios::app cannot help because you need to touch every line, not just the end of the file. As suggests, stream the original file line-by-line, write to a temporary file with the comma added before each newline, then swap the files. The snippet below is memory-safe for large files, avoids double-commas for lines that already end with one, and handles CRLF input cleanly.

#include <fstream>
#include <string>
#include <filesystem>

int main() {
    namespace fs = std::filesystem;
    const fs::path src = "a.txt";
    const fs::path tmp = src.string() + ".tmp";

    std::ifstream in(src);                       // text mode is fine
    std::ofstream out(tmp, std::ios::trunc);
    if (!in || !out) return 1;

    std::string line;
    while (std::getline(in, line)) {
        if (!line.empty() && line.back() == '\r') line.pop_back(); // CRLF safety
        out << line;
        if (line.empty() || line.back() != ',') out << ',';        // avoid double commas
        out << '\n';
    }

    in.close(); out.close();

    std::error_code ec;
    fs::rename(tmp, src, ec);                    // same-directory rename
    if (ec) { fs::remove(src); fs::rename(tmp, src); } // portable fallback
    return 0;
}

Notes:

  • If your goal was to replace newlines with commas (producing one long comma-separated line), omit the final out << '\n';.
  • Keep the temp file in the same directory as the original so the rename is fast and less error-prone.
  • Empty lines will become ,\n. If you do not want that, add a check to skip writing a comma for line.empty().

Recommended Answers

All 3 Replies

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.

Thanks Lucaci Andrew, that worked!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.