C Program to Count the Number of Lines in a File

C Program to Count the Number of Lines in a File

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file;
    char filename[100];
    char c;
    int line_count = 0;

    // Ask user for filename
    printf("Enter the filename: ");
    scanf("%s", filename);

    // Open file in read mode
    file = fopen(filename, "r");

    // Check if the file is opened successfully
    if (file == NULL) {
        printf("Could not open file %s\n", filename);
        return 1;
    }

    // Read each character from the file until EOF
    while ((c = fgetc(file)) != EOF) {
        // Count the newline character to count lines
        if (c == '\n') {
            line_count++;
        }
    }

    // Close the file
    fclose(file);

    // Print the total number of lines
    printf("The file %s has %d lines.\n", filename, line_count);

    return 0;
}

Explanation:

  1. Include headers: The program includes the stdio.h and stdlib.h headers. stdio.h is used for input/output operations like reading and writing to a file, while stdlib.h is used for standard library functions (though not strictly necessary in this program).
  2. Variable declaration:
    • FILE *file: A pointer to the file that is being opened.
    • filename[100]: A character array to store the name of the file that the user will input.
    • c: A variable to store the character being read from the file.
    • line_count: A counter that stores the number of lines in the file.
  3. User Input: The program prompts the user to enter the name of the file they want to count the lines for.
  4. File handling:
    • fopen(filename, "r"): The file is opened in read mode. If the file cannot be opened (due to not existing, permission issues, etc.), the program prints an error message and terminates.
  5. Loop:
    • The while loop reads each character from the file using fgetc(), checking for the newline character '\n'. Every time a newline character is encountered, the line count is incremented.
  6. File Closing: After reading the entire file, fclose() is called to close the file.
  7. Output: Finally, the program outputs the total number of lines in the file.

Program Output

Sample 1:

testfile.txt:

line 1
line 2
line 3
line 4
line 5
Input:
Enter the filename: testfile.txt

Output:
The file testfile.txt has 5 lines.

Sample 2:

Input:
Enter the filename: emptyfile.txt

Output:
The file emptyfile.txt has 0 lines.

Notes:

  • The program counts lines by detecting the newline character \n. Each \n is treated as the end of one line, so if a file has no newline characters (like an empty file or a single line without a newline at the end), it will report zero or fewer lines than expected.
  • Ensure the file exists in the same directory as the program or provide the full path.
Last updated on