Home »
C programs »
C file handling programs
C program to find number of lines in a file
By IncludeHelp Last updated : March 10, 2024
In this program, we are going to learn how to find total number of lines available in a text file using C program?
Finding number of lines in a file in C
This program will open a file and read file's content character by character and finally return the total number lines in the file. To count the number of lines we will check the available Newline (\n) characters.
File "test.text"
Hello friends, how are you?
This is a sample file to get line numbers from the file.
C program to find number of lines in a file
#include <stdio.h>
#define FILENAME "test.txt"
int main() {
FILE *fp;
char ch;
int linesCount = 0;
// open file in read more
fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("File \"%s\" does not exist!!!\n", FILENAME);
return -1;
}
// read character by character and check for new line
while ((ch = fgetc(fp)) != EOF) {
if (ch == '\n') linesCount++;
}
// close the file
fclose(fp);
// print number of lines
printf("Total number of lines are: %d\n", linesCount);
return 0;
}
Output
Total number of lines are: 2
Logic Explanation
1. Preprocessor Directive
#define FILENAME "test.txt" – It defines the name of the file to be read as test.txt.
2. Variable Declaration
- FILE *fp; - It is a pointer to the file object; we are using it to handle file operations.
- char ch; - It is used to stores the current character being read from the file.
- int linesCount = 0; - It is used to initialize the line count to zero, which will be incremented every time a newline (\n) character is encountered.
3. Opening the File
- fp = fopen(FILENAME, "r"); - It is used to open the file test.txt in read mode ("r").
- If the file cannot be opened (e.g., if the file does not exist), fp will be NULL. In this case, the program prints an error message and exits with a return code of -1.
4. Reading the File Character by Character
- The while loop reads the file character by character using fgetc(fp), which retrieves a single character from the file.
- fgetc(fp) returns EOF (End Of File) when the end of the file is reached, terminating the loop.
- Inside the loop, the program checks if the character read (ch) is a newline character ('\n'). If it is, the linesCount variable is incremented.
5. Closing the File
fclose(fp); - The statement is used to close the file to free up system resources.
6. Displaying the Result
The following statement is used to print the total number of lines counted in the file.
printf("Total number of lines are: %d\n", linesCount);
C File Handling Programs »