tags:

views:

255

answers:

2

hi can anyone show me how to get the total number of lines in a text file with programming language C? thanks!

+3  A: 

This is one approach:

FILE* myfile = fopen("test.txt", "r");
int ch, number_of_lines = 0;

do 
{
    ch = fgetc(myfile);
    if(ch == '\n')
     number_of_lines++;
} while (ch != EOF);

// last line doesn't end with a new line!
// but there has to be a line at least before the last line
if(ch != '\n' && number_of_lines != 0) 
    number_of_lines++;

fclose(myfile);

printf("number of lines in test.txt = %d", number_of_lines);
AraK
A: 

I think instead of providing the complete code, hint like "read each character and count new line character \n" could have been more useful. At least the questioner would have learned better as he had to code it himself.

Programmer in Paradise