The following code will find the total number of lines in a text file using C. The code uses C programming language’s built-in functions to access, open, read and count the number of lines of the text file.

Number of lines in a text file using C

#include <stdio.h>
int main()
{
    FILE *fptr;
    int count_lines = 0;
    char file_name[] = "replica.txt";
    char chr;

    fptr = fopen(file_name, "r");
    chr = getc(fptr);
    while (chr != EOF) {

        if (chr == '\n'){
            count_lines = count_lines + 1;
        }
        printf("%c",chr);
        chr = getc(fptr);
        if(count_lines>0&& chr==EOF)
            count_lines++;
    }
    fclose(fptr);
    printf("\n\nTotal Number of Lines: %d", count_lines);
    return 0;
}

Code Explanation

fopen(file_name, “r”) will open the file with file_name and saves the reference in FILE pointer. Once opened in the read mode, read the text in the file character by character. If the character is the newline character, increment the count of lines by one else keep reading till you found the End of File (EOF ) character.

Initialize the variable count_lines to zero, assuming that there is no line in the text file. As you encounter the first newline character, update the count_lines to 1.

To count the last line, use the following:

if(count_lines>0&& chr==EOF)
count_lines++;

This above is particularly useful if the user didn’t enter a new line after the last line and it meets EOF character by default.

Recommended reading

Last modified: March 21, 2019