C Program to Count the Number of Lines in a File

In this article, we will write a C program to count the number of lines in a file. The program prompts the user to enter the name of the file, checks if that file exists or not and counts the total number of lines in that file. Finally, it prints the result on the output window.

Sample Input:

Enter the name of the file: myfile.txt

Sample Output:

The number of lines in the file are: 5

The basic idea of counting the total number of lines in a file is to read the complete file character by character and increment the line count by one as soon as we encounter a new line character('\n').

This process continues until we reach the end of the file. To detect that we can compare if the current character is equal to the EOF character.

To achieve these two tasks, we need two built-in functions. First, the fopen() function and second the fgetc() function.

The fopen() function is used to open a file in the specified mode such as read, write, append, etc. Whereas the fgetc() function helps us to read the file character by character.

The fopen() function takes two arguments, first, the name of the file which we want to open and second the mode in which we want to open that file.

It has the following syntax:

FILE *fopen(const char *filename, const char *mode);

As we want to only count the total number of lines in the given file, therefore, we need to open it in read-only mode which is specified by "r".

See the implementation in the below program:

// C program to count the
// total number of lines in a file

#include <stdio.h>

int main(){
	
	char filename[100], ch;
	FILE *fptr;
	int lineCount = 0;
	
	
	printf("Enter the name of the file: ");
	scanf("%s", &filename);
	
	// Open the file in Read mode
	fptr = fopen(filename, "r");
	
	// Check if there is an error opening the file
	if(fptr == NULL){
		printf("Error opening the file");
		return 1;
	}
	
	
	// Read the first character of the file
	ch = fgetc(fptr);
	
	// Read file characters until EOF(End of file) is reached
	while(ch!=EOF){
		// Increment line count by one if newline char is detected
		if(ch == '\n'){
			lineCount += 1;
		}
		
		// Read next character
		ch = fgetc(fptr); 
	}
	
	printf("The number of lines in the file are: %d", lineCount);
	
	// Close the file
	fclose(fptr);
	
    return 0;
    
}

Output:

Enter the name of the file: myfile.txt
The number of lines in the file are: 5

Enter the name of the file: random.txt
Error opening the file

Below is a screenshot of the file we are counting lines in:

Input of C program to count the number of lines in a file

Program Explanation

Here is a detailed explanation of the above program:

  • User Input:
    • The program starts by prompting the user to enter the name of the file for which he wants to count the number of lines.
    • The file name entered by the user is stored in the filename character array.
  • File Pointer Declaration:
    • It declares a file pointer fptr of type FILE that will be used to work with the file.
  • File Opening in Read Mode:
    • The program opens the file specified by filename in read mode (“r”) using fopen().
    • After that error checking is performed to ensure that the file was successfully opened. If fptr is NULL, it indicates an error.
  • Character Reading Loop:
    • The program initializes a character variable ch and enters a while loop to read the file character by character using the fgetc() function.
    • The loop continues until the end of the file (EOF) is reached.
  • Line Counting:
    • Inside the loop, it checks if the current character ch is a newline character ('\n'). If it is, it increments the lineCount variable by one to count the line.
    • After processing each character, the program reads the next character from the file using fgetc() function.
  • Result Display and File Closure:
    • Once it has processed the entire file and counted the lines, the program prints the total number of lines counted.
    • Finally, it closes the file using fclose(fptr) to release system resources.

I hope you like this article. Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts