Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert .txt file from CRLF to LF and back

I want to write a little function that takes a file as input, and writes to an output file with the following changes:

  • If the input file uses CRLF (\r\n) as EndOfLine, it should be replaced with only LF (\n).
  • If it uses LF (\n), those should be replaced with CRLF (\r\n)

See this post for a bit more info on this.

Here’s my attempt at doing this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool convertFile(string location) {
    ifstream input;
    ofstream output;

    input.open(location); 

    if(!input.is_open()){
        cout << "Invalid location!" << endl;
        return false;
    }

    int dot = location.find_last_of('.');
    if(dot != string::npos) location.replace(dot, 1, "_new.");
    output.open(location);


    char c;
    for(;;){
        input.get(c);
        if(!input.good()){
            if(input.eof()) return true;
            else return false;
        } 
        if(c == '\r'){
            input.get(c); 
            if(c == '\n') output << '\n'; // \r\n -> \n
            else output << '\r' << c; // leave as it was, I dont know if this is needed
        } else if (c == '\n'){
            output << "\r\n"; // \n -> \r\n
        } else {
            output << c;
        }
    }

However, that doesn’t work as expected.

With this input:
input

I get this output:
output

I tried solving this by debugging my script, and what I found is that if(c == '\r') never evaluates to true, so it seems like I have no \r’s in my .txt, which notepad++ says I do.

I am on windows, and that’s the only thing I can think of that might cause this, but I don’t know how.
(Also, sorry for the bad formatting, I couldn’t get it to look better with the images)

>Solution :

When you open a file in text mode, the input stream will already convert line endings. Open the file in binary mode if you want full control.

input.open(location, std::ios::binary);
output.open(location, std::ios::binary);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading