C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

File Handling in C

Count characters in file

C Program: Count characters in file

C

#include <stdio.h>

 

int main() {

    FILE *file;

    char filename[100];

    char ch;

    int count = 0;

 

    // Step 1: Get file name from user

    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 end of file

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

        count++;

    }

 

    // Step 5: Display result

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

 

    // Step 6: Close file

    fclose(file);

 

    return 0;

}

Output

 
INPUT :
Enter file name: sample.txt

File Content sample.txt:

Hello World
C Programming

Output : 
Total number of characters in the file: 25

Explanation

Step

Description

1

Prompts the user to enter the file name.

2

Opens the file in read mode ("r").

3

If file can’t be opened, prints an error.

4

Uses fgetc() to read every character until EOF (end of file).

5

Increments count for every character read.

6

Prints the total number of characters.