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
- Ask the user to enter a file name.
- Initialize a variable count = 0 to store the black spaces count.
- 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.
- 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