C documentation V1 Help

Program: Finding the Total Number of Lines in a Text File

Problem Statement

Write a C program to find the total number of lines in a text file. Create a file containing some lines of text, open the file, use the fgetc function to parse characters until the end of the file (EOF), and increment a counter for each encountered EOF to determine the total number of lines. Display the total number of lines in the file as output.

Algorithm

  1. Open File:

    • Open the text file using the fopen function.

    FILE *filePointer; filePointer = fopen("testfile.txt", "r");
    • Check if the file is successfully opened.

    if (filePointer == NULL) { // Handle file opening error }
  2. Count Lines:

    • Initialize a counter to keep track of the lines.

    int lineCount = 0;
    • Use a loop to read characters from the file until the end of the file (EOF).

    int character; while ((character = fgetc(filePointer)) != EOF) { // Check for new line character if (character == '\n') { // Increment line count lineCount++; } }
  3. Display Output:

    • Display the total number of lines as output.

    printf("Total number of lines: %d\n", lineCount);
  4. Close File:

    • Always close the file after operations using the fclose function.

    fclose(filePointer);

Explanation

This program reads characters from a text file using fgetc until the end of the file is reached. While parsing, it checks for newline characters ('\n') and increments a counter for each occurrence. The final count represents the total number of lines in the file, which is then displayed as output.

This approach provides a simple way to determine the number of lines in a text file without using more advanced file reading techniques.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024