Important: Please read the Qt Code of Conduct -

Read a file and distinguish CR/LF and LF char

  • Hello everybody

    Happy new year all of you!

    I come here because I need some help about file reading. Actually, I have a program that read a file through QTextStream. But now, I have to distinguish CR/LF and LF new line character. In fact, I want to know if each line in the file ended with CR/LF or with LF, knowing that the file have some line that finished by CR/LF and some other that finish by LF.

    Thanks a lot for your help.

  • Use QTextStream::readLine and you will get every line which ends with CR/LF or LF (you will get it without them!)

  • But it is what I want: to get the "\n" or the "\r\n" into the read string. And QTextStream do not return the "end of line" character.

  • QTextStream::readAll does contain all the whitespaces. If you want their position you might use QString::indexOf

  • The problem is I'm working with huge files (sometime more than 200 MB of text). So I can't use readAll() because it load all the file content in memory.

    No, I'd like to read the file line by line. Maybe I have to subclass QFile and create my own reading method using readLineData()... But I wanted to be sure there is not an already existing solution for this problem ;)

  • And why don't use readLine and just append LF or CR/LF?

  • Because it is exactly what I want to know: In the file, there is some line ended by CR/LF and some other ended by LF (which I internaly do not treat like a real end of line, but as a new line in the data itself). Well it is a bit tricky.

    But to summarize, the file containts some lines with CR/LF and some lines with LF. And I want to know when I'm reading the file if the line I'm reading is ended by CR/LF or by LF.

  • Moderators


    If you use a text stream, or if you use QIODevice::Text when you open the file, Qt will convert all CR/LF to LF.

    To preserve them, you will need to read your data as raw bytes, and then search for "\r\n" manually.


Log in to reply