C Program to Count Number of Blank Spaces in a File

Write a program to count the number of blacks spaces in a file in C.

For example,

Content of Input File
My name is John Smith
I am 14 years old
I Likes to play video games
Output
Number of blank spaces = 13

Steps

  1. Ask the user to enter a file name.
  2. Initialize a variable count = 0 to store the black spaces count.
  3. Read the content of the file character by character. Use a conditional statement to check if a character is a black space or not. If a character is a blank space, increment count.
  4. The number of blank spaces in the input file is equal to count.
#include <stdio.h>
// returns the number of black spaces in the file

int blank_spaces(char file[256]) 
{
	
    FILE* fp;
    char c;
    int count = 0;    // variable to store black spaces count
    fp = fopen(file, "r");
    
    if (fp == NULL) 
	{
        printf("UNABLE TO OPEN THE FILE");
        return -1;
    }
    
    while ((c = fgetc(fp)) != EOF) 
	{
        if (c == ' ')
            ++count;
    }
    
    return count;
    
}

// function to print content of a file
void print_file(char file[256]) 
{
	
    FILE* fp;
    char c;
    fp = fopen(file, "r");
    
    if (fp == NULL) {
        printf("UNABLE TO OPEN THE FILE");
    }
    while ((c = fgetc(fp)) != EOF) {
        printf("%c", c);
    }
    
}

int main()
{
    char file[256];
    printf("Enter file name: ");
    gets(file);
    printf("\n***CONTENT OF THE INPUT FILE***\n");
    print_file(file);
    printf("\n");
    printf("Number of Black spaces = %d", blank_spaces(file));
}

Output

Enter file name: text.txt

***CONTENT OF THE INPUT FILE***
My name is John Smith
I am 14 years old
I Likes to play video games

Number of Black spaces = 13

Read

  1. Program to search for a word in a file and print all it’s positions in C
  2. C Program to count the number of uppercase and lowercase letters

Leave a Comment

Your email address will not be published. Required fields are marked *