C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Count words in file

C Program: Count words in file

C

#include <stdio.h>

#include <ctype.h>

 

int main() {

    FILE *file;

    char filename[100];

    char ch;

    int words = 0, inWord = 0;

 

    // Step 1: Get the file name from the user

    printf("Enter file name: ");

    scanf("%s", filename);

 

    // Step 2: Open the file in read mode

    file = fopen(filename, "r");

 

    // Step 3: Check if file exists

    if (file == NULL) {

        printf("Error! Cannot open file.\n");

        return 1;

    }

 

    // Step 4: Read file character by character

    while ((ch = fgetc(file)) != EOF) {

        if (isspace(ch)) {

            // If space or newline, mark end of word

            inWord = 0;

        } else if (inWord == 0) {

            // Start of a new word

            inWord = 1;

            words++;

        }

    }

 

    // Step 5: Print total word count

    printf("Total number of words in the file: %d\n", words);

 

    // Step 6: Close the file

    fclose(file);

 

    return 0;

}

Output

 
File Content (sample.txt) :
Hello world
Welcome to C programming

Output : 
Total number of words in the file: 5

Explanation

Step

Description

1

Takes filename input from the user.

2

Opens file in "r" (read) mode.

3

Checks if file exists; if not, prints error.

4

Uses fgetc() to read one character at a time.

5

isspace(ch) checks for space, newline, or tab — word separators.

6

Counts new words whenever a non-space character starts after a space.

7

Prints total number of words found.