C Count Words in a File Program
Counting the number of words in a file is a common programming task that demonstrates file handling and string manipulation in C. Below is a simple C program that reads a text file and counts the number of words it contains.
Program: Count Words in a File in C
Explanation of the Program
Header Files:
#include <stdio.h>
: For standard I/O functions.#include <stdlib.h>
: For exit status and error handling.#include <ctype.h>
: For character type functions likeisalpha()
andisdigit()
.
File Pointer:
FILE *file;
: Declares a pointer to handle the file.
Variables:
char ch;
: To store each character read from the file.int inWord = 0;
: A flag to track whether the program is currently inside a word.int wordCount = 0;
: Counter to keep track of the number of words.
Open the File:
- The program attempts to open
input.txt
in read mode: - If the file cannot be opened, it prints an error message and exits.
- The program attempts to open
Read Characters:
- The program reads characters from the file in a loop until it reaches the end-of-file (
EOF
):
- The program reads characters from the file in a loop until it reaches the end-of-file (
Count Words:
- Inside the loop, it checks if the character is a letter or digit using
isalpha()
andisdigit()
:- If
inWord
is0
, it means the program has found a new word. It setsinWord
to1
and increments thewordCount
:
- If
- If the character is not a letter or digit, the program sets
inWord
to0
, indicating that it has exited a word.
- Inside the loop, it checks if the character is a letter or digit using
Print Word Count:
- After processing the file, the program prints the total number of words:
- After processing the file, the program prints the total number of words:
Close the File:
- Finally, it closes the file to release resources:
- Finally, it closes the file to release resources:
How to Run the Program
Create the Input File: Create a text file named
input.txt
in the same directory as the program and add some text to it.Compile the Code: Use a C compiler like
gcc
to compile the code:Execute the Program: Run the compiled program:
Example Output
Assuming input.txt
contains the following text:
After running the program, the output will be:
Conclusion
This program effectively counts the number of words in a file by reading it character by character. It uses simple logic to identify words based on the presence of letters and digits, while treating spaces and punctuation as delimiters. This approach can be extended or modified for more complex word counting scenarios, such as handling hyphenated words, contractions, or specific punctuation rules.