5 years, 1 month ago.

simple command to output the number of lines of a text document?

Hello Community, I want to read from a text document the number of rows. My solution is definitely not the best:

LocalFileSystem local("local");

char buffer[128];

int u;

int main ()

{

FILE *fp1 = fopen("/local/Trace.txt","r");

while(fgets(buffer, 128, fp1)) {

u=u++;

}

printf("rows: %d ",u);

fclose(fp1);

...

Is there a simple command to output the number of lines of a text document? Or someone has a nicer solution?

Thank you

1 Answer

5 years, 1 month ago.

There is not much wrong with your solution. Instead of u=u++; just write u++; You could save some memory and avoid the hard limit on the line length by not reading a line at a time but a character at a time using fgetc() and counting the number of '\n'. If all your lines are the same length you could calculate the number of lines as filesize/linelength.