This thinking comes from a discussion about a practical problem Replacing multiple new lines in a file with just one. Something wrong happened while using a cygwin terminal running on a windows 8.1 machine.
Since the end-of-line terminator would be different, like \n
, \r
, or \r\n
, is it necessary to write a "portable" if(c=='\n')
to make it work well on Linux, Windows and OS X? Or, the best practise is just to convert the file with commands/tools?
#include <stdio.h>
int main ()
{
FILE * pFile;
int c;
int n = 0;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
do {
c = fgetc (pFile);
if (c == '\n') n++; // will it work fine under different platform?
} while (c != EOF);
fclose (pFile);
printf ("The file contains %d lines.\n",n);
}
return 0;
}
Update1:
CRT will always convert line endings into '\n'?