Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving total line numbers in a file

Tags:

c

file

text

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

like image 421
asel Avatar asked Dec 15 '09 22:12

asel


People also ask

How do I count the number of lines in a file named test file?

But one of the easiest and widely used way is to use “wc -l”. The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output. 1. The “wc -l” command when run on this file, outputs the line count along with the filename.

How do I count the number of lines in a file in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do I count the number of lines in a file without opening the file?

If you are in *Nix system, you can call the command wc -l that gives the number of lines in file.


1 Answers

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);
like image 94
Khaled Alshaya Avatar answered Sep 20 '22 04:09

Khaled Alshaya