This is a C program that counts the number of lines, words and characters in a text file. At first the program prompts the user to enter the name of the file to be checked. The filename is passed as a parameter to the C Library function, fopen(). The second parameter "r"
of the fopen function specifies the file should be opened in read only mode. The fopen function returns a pointer to the FILE object if the file is opened successfully.
The file is then read one character at a time using the fgetc() library function inside a while loop until the End of File (EOF) is reached. Character count is incremented with each iteration of the loop, word count is incremented when a Space character is encountered and line count is incremented for each new line character that is read.
Finally, linecount and wordcount are incremented by one if the character count is more than zero. Without this step the final word and line won't be counted.
Program Source Code
/************************************************* * C program to count no of lines, words and * * characters in a file. * *************************************************/ #include <stdio.h> int main() { FILE *fp; char filename[100]; char ch; int linecount, wordcount, charcount; // Initialize counter variables linecount = 0; wordcount = 0; charcount = 0; // Prompt user to enter filename printf("Enter a filename :"); gets(filename); // Open file in read-only mode fp = fopen(filename,"r"); // If file opened successfully, then write the string to file if ( fp ) { //Repeat until End Of File character is reached. while ((ch=getc(fp)) != EOF) { // Increment character count if NOT new line or space if (ch != ' ' && ch != '\n') { ++charcount; } // Increment word count if new line or space character if (ch == ' ' || ch == '\n') { ++wordcount; } // Increment line count if new line character if (ch == '\n') { ++linecount; } } if (charcount > 0) { ++linecount; ++wordcount; } } else { printf("Failed to open the file\n"); } printf("Lines : %d \n", linecount); printf("Words : %d \n", wordcount); printf("Characters : %d \n", charcount); getchar(); return(0); }
Sample Output
Consider a text file named wolf.txt
with the following content:
Help Help, Go away you naughty wolf.
With the above file as input, the program will be show the result as below
Enter a filename :wolf.txt Lines : 2 Words : 7 Characters : 30