How to Count Lines in a File in C: Simple Example and Tips
To count lines in a file in C, open the file with
fopen, then read it line by line using fgets or character by character with fgetc, incrementing a counter each time you find a newline character '\n'. Close the file with fclose after counting.Syntax
Here is the basic syntax to count lines in a file using fgetc:
FILE *file = fopen("filename.txt", "r");opens the file for reading.int ch;stores each character read.while ((ch = fgetc(file)) != EOF)loops through each character until the end of file.if (ch == '\n')checks if the character is a newline to count lines.fclose(file);closes the file when done.
c
FILE *file = fopen("filename.txt", "r"); int ch; int lines = 0; if (file) { while ((ch = fgetc(file)) != EOF) { if (ch == '\n') { lines++; } } fclose(file); }
Example
This example opens a file named example.txt, counts how many lines it contains, and prints the result.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Could not open file.\n"); return 1; } int ch; int lines = 0; while ((ch = fgetc(file)) != EOF) { if (ch == '\n') { lines++; } } fclose(file); printf("Number of lines: %d\n", lines); return 0; }
Output
Number of lines: 4
Common Pitfalls
Common mistakes when counting lines in a file include:
- Not checking if the file opened successfully before reading.
- Not counting the last line if it does not end with a newline character.
- Using
feof()incorrectly to control the loop, which can cause off-by-one errors.
To handle files without a trailing newline, you can add 1 to the count if the file is not empty and the last character is not a newline.
c
#include <stdio.h> int main() { FILE *file = fopen("example.txt", "r"); if (file == NULL) { printf("Could not open file.\n"); return 1; } int ch; int lines = 0; int last_char = 0; while ((ch = fgetc(file)) != EOF) { if (ch == '\n') { lines++; } last_char = ch; } if (last_char != '\n' && last_char != 0) { lines++; } fclose(file); printf("Number of lines: %d\n", lines); return 0; }
Output
Number of lines: 5
Quick Reference
Tips for counting lines in C files:
- Always check if
fopenreturnsNULLbefore reading. - Use
fgetcorfgetsto read file content safely. - Count newline characters
'\n'to track lines. - Remember to close the file with
fcloseto free resources. - Handle files without trailing newline by checking the last character read.
Key Takeaways
Open the file with fopen and always check for NULL to avoid errors.
Count lines by reading characters and incrementing when you find '\n'.
Close the file with fclose after finishing reading.
Handle files without a trailing newline by checking the last character read.
Avoid using feof() to control reading loops to prevent off-by-one errors.