C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Count vowels, consonants, digits and space in file

C Program: Count vowels, consonants, digits and space in file

C

#include <stdio.h>

#include <ctype.h>

 

int main() {

    FILE *file;

    char filename[100];

    char ch;

    int vowels = 0, consonants = 0, digits = 0, spaces = 0;

 

    // Step 1: Ask for file name

    printf("Enter file name: ");

    scanf("%s", filename);

 

    // Step 2: Open 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 each character until EOF

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

        ch = tolower(ch); // Convert to lowercase for simplicity

 

        if (ch >= 'a' && ch <= 'z') {

            // Check vowels

            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')

                vowels++;

            else

                consonants++;

        }

        else if (ch >= '0' && ch <= '9')

            digits++;

        else if (ch == ' ')

            spaces++;

    }

 

    // Step 5: Display results

    printf("\nVowels: %d", vowels);

    printf("\nConsonants: %d", consonants);

    printf("\nDigits: %d", digits);

    printf("\nSpaces: %d\n", spaces);

 

    // Step 6: Close the file

    fclose(file);

 

    return 0;

}

Output

 
File Content  (data.txt) :

 C Programming 2025 is Fun!

OUTPUT :
Vowels: 6
Consonants: 10
Digits: 4
Spaces: 3

Explanation

Step

Description

1

Prompts user for file name.

2

Opens file in read mode.

3

Validates that file exists.

4

Reads each character using fgetc().

5

Uses conditions to classify vowels, consonants, digits, and spaces.

6

Displays the total counts.

7

Closes the file.