C Program to Count Characters, Words,
and Lines Without Inbuilt Functions
Below is a C program to count the number of characters, words, and lines in a text file
without using inbuilt functions like `fgetc()` or `isspace()`. The program uses `getc()` and
manual checks for whitespace characters.
#include <stdio.h>
int main() {
FILE *fp = fopen("text.txt", "r");
if (fp == NULL) {
printf("File not found.\n");
return 1;
}
char ch;
int charCount = 0, wordCount = 0, lineCount = 0, inWord = 0;
while (1) {
ch = getc(fp); // basic function to get character from file
if (ch == EOF)
break;
charCount++;
if (ch == '\n')
lineCount++;
// check for whitespace manually (space, tab, newline)
if (ch == ' ' || ch == '\t' || ch == '\n') {
inWord = 0;
} else if (inWord == 0) {
inWord = 1;
wordCount++;
}
}
fclose(fp);
printf("Characters: %d\nWords: %d\nLines: %d\n", charCount,
wordCount, lineCount);
return 0;
}