I’m following a book on c, and I come to some code that reads a file with 3 lines of text.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *fp;
int c;
fp = fopen( "../../My Data File", "r" );
if ( NULL == fp ) {
printf( "Error opening ../My Data File" );
} else {
while ( (c = fgetc( fp )) != EOF )
putchar ( c );
fclose( fp );
}
return 0;
}
I tried to modify it, to detect each line and print the current line number by making these modifications.
int line = 1;
while ( (c = fgetc( fp )) != EOF ){
if (c == '\n'){
printf(" LINE %d", line);
putchar( c );
line++;
}
else {
putchar ( c );
}
}
But it failed to print the line #, till I changed the type of the variable c to a char. Is there a way to check for a newline while still using c as an int?
What is the proper way to check for a newline?
Your code prints line numbers at the end of a line, right before printing the
'\n', because of the way you have written the loop. Otherwise, your code should work.If you want your code to print the line numbers at the beginning, you can do something like (untested):
If there is something else that “doesn’t work”, you should post complete code and tell us what doesn’t work.
Edit: The proper way to check a character for a newline is to test against
'\n'. If the character came from a file, you should also make sure you open the file in text mode, i.e., without abin the second argument tofopen().Also, you want
cto be of typeint, notchar. This is because in C,EOFis a small negative number, and ifcharis unsigned, comparing it against a negative number convert the value ofEOFto a positive value (equal toEOF + UCHAR_MAX + 1most likely). Therefore, you should not changectochartype. If you do, the comparisonc != EOFmight be false even whenfgetc()returnsEOF.