Sunday 15 August 2010

C detect the last new line at the end of the file -



C detect the last new line at the end of the file -

i can't observe new line after before end of file if new line have text on previous line.

i can observe new line 4

1 text 2 text 3 4

but not new line 3 type of file

1 text 2 text 3

(the number (1,2,3,4) lines, not in file)

there sample code : (edit: code updated more relevant variable)

#include <stdio.h> #include <string.h> main() { file *fp; int ch; int = 0; int line = 1; int column = 0; int tmp = 0; fp = fopen("input.txt", "r"); if( fp != null ){ while((ch = fgetc(fp)) != eof) { switch(ch) { case '\n': if(i == 0) { column = tmp; } if(tmp != column) { printf("error\n"); } tmp = 0; line++; i++; break; default: tmp++; break; } } fclose(fp); } }

i don't understand why there not output "error" in sec case.

your code counts number of characters in file before first newline, , stores n. each subsequent time reads newline, checks whether number of characters read since previous newline same number of characters on first line (n), , prints error message if not (which seems bit odd).

have considered newlines in input, , definition of "line" is? think find there 3 newlines in four-line text, , 2 in three-line text. is, editor presenting lastly line of file not terminated newline.

c file fgetc

No comments:

Post a Comment