Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to count characters, lines and number of words in a file
In C programming, counting characters, words, and lines in a file is a common file processing task. This operation reads through a file character by character and keeps track of different elements based on specific delimiters.
Syntax
FILE *fopen(const char *filename, const char *mode); int fgetc(FILE *stream); int fclose(FILE *stream);
File Operations Overview
The three basic operations that we can perform on files are −
- Open a file − Using fopen() function
- Process file − Read, write, or modify file contents
- Save and close file − Using fclose() function
Example: Counting File Content
The following program demonstrates how to count characters, words, and lines in a text file −
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char filename[100];
char ch;
int characters = 0, words = 0, lines = 0;
int inWord = 0;
printf("Enter filename: ");
scanf("%s", filename);
file = fopen(filename, "r");
if (file == NULL) {
printf("Error: Unable to open file '%s'<br>", filename);
return 1;
}
while ((ch = fgetc(file)) != EOF) {
characters++;
if (ch == '<br>') {
lines++;
if (inWord) {
words++;
inWord = 0;
}
}
else if (ch == ' ' || ch == '\t') {
if (inWord) {
words++;
inWord = 0;
}
}
else {
inWord = 1;
}
}
/* Count the last word if file doesn't end with newline */
if (inWord) {
words++;
}
/* Count the last line if file doesn't end with newline */
if (characters > 0) {
lines++;
}
printf("\nFile Statistics:<br>");
printf("Total characters = %d<br>", characters);
printf("Total words = %d<br>", words);
printf("Total lines = %d<br>", lines);
fclose(file);
return 0;
}
How It Works
The program uses the following logic −
- Character counting − Increments counter for each character read
- Word counting − Uses a flag to track when inside a word, counts transitions from word to non-word
- Line counting − Increments counter at each newline character
Sample Input File
Create a text file named sample.txt with the following content −
Hello World This is C programming Tutorial from TutorialsPoint
Output
When you run the program with the above input file, it produces −
Enter filename: sample.txt File Statistics: Total characters = 58 Total words = 8 Total lines = 3
Key Points
- Always check if file opens successfully before processing
- Use
fgetc()to read one character at a time - Handle edge cases like files not ending with newline
- Close the file with
fclose()to free resources
Conclusion
File content analysis in C involves reading character by character and tracking delimiters. This approach provides accurate counting of characters, words, and lines in any text file using standard C library functions.
