C PROGRAMMING PROGRAM • FILE HANDLING
Count Characters, Words and Lines in a File
Learn how to count characters, words and lines in a file using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Characters = 55 Words = 7 Lines = 2
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <ctype.h>
int main(void)
{
const char *sample = "C programming is powerful.\nPractice builds confidence.\n";
FILE *file = fopen("sample.txt", "w");
if (file == NULL) return 1;
fputs(sample, file);
fclose(file);
file = fopen("sample.txt", "r");
if (file == NULL) return 1;
long characters = 0, words = 0, lines = 0;
int character, insideWord = 0, last = '\0';
while ((character = fgetc(file)) != EOF) {
characters++;
if (character == '\n') lines++;
if (isspace((unsigned char) character)) insideWord = 0;
else if (!insideWord) { words++; insideWord = 1; }
last = character;
}
if (characters > 0 && last != '\n') lines++;
fclose(file);
printf("Characters = %ld\nWords = %ld\nLines = %ld\n", characters, words, lines);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Characters = 55 Words = 7 Lines = 2
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Read one character at a time, count newlines and detect transitions into words.
- Display the computed result.
Read one character at a time, count newlines and detect transitions into words.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
