asel
asel

Reputation: 1109

Retrieving total line numbers in a file

can someone show me how to get the total number of lines in a text file in programming language C?

Upvotes: 5

Views: 33659

Answers (2)

Rolfadolf
Rolfadolf

Reputation: 9

A "not by a project manager" solution

system("wc profile.dat > no.lines"); 
FILE *pfile = fopen("no.lines", "r");
int lines; 
fscanf(pfile, "%d", &lines); 
system("rm no.lines");

Upvotes: -5

Khaled Alshaya
Khaled Alshaya

Reputation: 96849

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

Upvotes: 20

Related Questions