How to Count Words in a File in C: Simple Example
To count words in a file in C, open the file using
fopen, then read it word by word using fscanf with the %s format specifier, incrementing a counter for each word read until the end of the file is reached. Finally, close the file with fclose and use the counter as the total word count.Syntax
To count words in a file, you typically use these steps:
FILE *fp = fopen(filename, "r");- Open the file for reading.while (fscanf(fp, "%s", buffer) == 1)- Read each word into a buffer.count++;- Increase the word count for each successful read.fclose(fp);- Close the file after reading.
c
FILE *fp = fopen("file.txt", "r"); char buffer[100]; int count = 0; if (fp == NULL) { // Handle error } while (fscanf(fp, "%99s", buffer) == 1) { count++; } fclose(fp);
Example
This example shows how to open a file named sample.txt, count the words inside it, and print the total count.
c
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("sample.txt", "r"); if (fp == NULL) { printf("Could not open file\n"); return 1; } char word[100]; int count = 0; while (fscanf(fp, "%99s", word) == 1) { count++; } fclose(fp); printf("Total words: %d\n", count); return 0; }
Output
Total words: 42
Common Pitfalls
Common mistakes when counting words in a file include:
- Not checking if the file opened successfully before reading.
- Using a buffer too small for words, which can cause overflow.
- Not handling punctuation or special characters if precise word counting is needed.
- Forgetting to close the file, which can cause resource leaks.
Always check fopen return value and use a safe buffer size.
c
/* Wrong: No file open check and small buffer */ FILE *fp = fopen("file.txt", "r"); char word[10]; int count = 0; while (fscanf(fp, "%s", word) == 1) { count++; } fclose(fp); /* Right: Check file and use larger buffer */ FILE *fp2 = fopen("file.txt", "r"); if (fp2 == NULL) { printf("Error opening file\n"); return 1; } char word2[100]; int count2 = 0; while (fscanf(fp2, "%99s", word2) == 1) { count2++; } fclose(fp2);
Quick Reference
- Open file:
fopen(filename, "r") - Read word:
fscanf(fp, "%s", buffer) - Count words: Increment counter each successful read
- Close file:
fclose(fp)
Key Takeaways
Always check if the file opened successfully before reading.
Use fscanf with "%s" to read words one by one safely.
Increment a counter for each word read until EOF.
Close the file after finishing to free resources.
Use a sufficiently large buffer to avoid overflow.