C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Count lines in file

C Program: Count lines in file

C

#include <stdio.h>

 

int main() {

    FILE *file;

    char filename[100];

    char ch;

    int lines = 0;

 

    // Step 1: Get the file name from the user

    printf("Enter file name: ");

    scanf("%s", filename);

 

    // Step 2: Open file in read mode

    file = fopen(filename, "r");

 

    // Step 3: Check if file exists

    if (file == NULL) {

        printf("Error! Cannot open file.\n");

        return 1;

    }

 

    // Step 4: Read file character by character

    while ((ch = fgetc(file)) != EOF) {

        if (ch == '\n') {

            lines++;

        }

    }

 

    // Step 5: Handle the case if file doesn’t end with newline

    lines++;

 

    // Step 6: Display total line count

    printf("Total number of lines in the file: %d\n", lines);

 

    // Step 7: Close file

    fclose(file);

 

    return 0;

}

Output

 
File Content (data.txt) :
C programming is fun.
It is powerful.
It is fast.

Output : 
Total number of lines in the file: 3

Explanation

Step

Description

1

Prompts user for filename.

2

Opens file in "r" (read) mode.

3

Validates file existence.

4

Reads file character-by-character using fgetc().

5

Increments line count for every newline character '\n'.

6

Adds one more line if the last line doesn’t end with newline.

7

Displays total number of lines.