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:
- Include headers: The program includes the
stdio.h
andstdlib.h
headers.stdio.h
is used for input/output operations like reading and writing to a file, whilestdlib.h
is used for standard library functions (though not strictly necessary in this program). - 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.
- User Input: The program prompts the user to enter the name of the file they want to count the lines for.
- 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.
- Loop:
- The
while
loop reads each character from the file usingfgetc()
, checking for the newline character'\n'
. Every time a newline character is encountered, the line count is incremented.
- The
- File Closing: After reading the entire file,
fclose()
is called to close the file. - 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