Search code examples
cfiletextcarriage-returnend-of-line

End of line character / Carriage return


I'm reading a normal text file and write all the words as numbers to another text. When a line finishes it looks for a "new line character (\n)" and continues from the new line. In Ubuntu it executes perfectly but in Windows (DevC++) it cannot operate the function. My problem is the text in Windows which I read haven't got new line characters. Even I put new lines by my hand my program cannot see it. When I want to print the character at the end of the line, it says it is a space (ascii = 32) and I am sur that I am end of the line. Here is my end of line control code, what can I do to fix it? And I read about a character called "carriage return (\r)" but it doesn't fix my problem either.

c = fgetc(fp);
printf("%d", c);
fseek(fp, -1, SEEK_SET);
if(c == '\n' || c == '\r')
    fprintf(fp3, "%c%c", '\r', '\n');

Solution

  • If you are opening a text file and want newline conversions to take place, open the file in "r" mode instead of "rb"

    FILE *fp = fopen(fname, "r");
    

    this will open in text mode instead of binary mode, which is what you want for text files. On linux there won't appear to be a difference, but on windows, \r\n will be translated to \n

    A possible solution it seems, is to read the numbers out of your file into an int variable directly.

    int n;
    fscanf(fp, "%d", &n);
    

    unless the newline means something significant to you.