mrtgnccn
mrtgnccn

Reputation: 173

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');

Upvotes: 2

Views: 13542

Answers (2)

akn
akn

Reputation: 56

There are a couple of questions here

  1. What is the difference between windows text newline and unix text newline?

    UNIX newline is LF only. ASCII code 0x0a. Windows newline is CR + LF. ASCII code 0x0d and 0x0a

  2. Does your file have LF or CR ?

    Use a hex editor to see the contents of the file. I use xxd on linux.

    $ xxd unix.txt
    0000000: 0a0a 
    $ xxd windows.txt
    0000000: 0d0a 
    

Upvotes: 0

Ryan Haining
Ryan Haining

Reputation: 36792

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.

Upvotes: 2

Related Questions