Count Number of Spaces, Newlines, Tabs C Program

By | December 10, 2015

C Program To Count Number of Spaces, Newlines, Tabs in File

Learn How to Count the Number of Spaces, Tabs, Characters and Newlines in a Text File in C Programming Language. This

How Do We Recognize and Count Number of Spaces, Newlines, Tabs and Characters in File? Simple!

Compare every occurring character with each of them:
if(ch == ‘ ‘) This will check the occurrence of Spaces within the Text file.
if(ch == ‘\n’) This condition will will check the Number of Newlines.
if(ch == ‘\t’) This condition will check the Number of Tabs.

Also Read: C Program To Read Contents of a File

C Program To Count Number of Spaces, Newlines, Tabs and Characters in File

#include<stdio.h>
#include<stdlib.h>

void main()
{
    FILE *fp;
    char ch;
    int character = 0, space = 0, tab = 0, line = 0;
    fp = fopen("/home/tusharsoni/Desktop/TestFile","r");
    if(fp == NULL)
    {
        printf("File Not Found\n");
        exit(1);
    }
    else
    {
        while(1)
        {
            ch = fgetc(fp);
            if(ch == EOF)   
            {
                break;
            }
            character++;
            if(ch == ' ')
                space++;
            else if(ch == '\t')
                tab++;
            else if(ch == '\n')
                line++;
        }
    }
    fclose(fp);
    printf("\nNumber of Characters = %d\n", character);
    printf("\nNumber of Tabs       = %d\n", tab);
    printf("\nNumber of New Lines  = %d\n", line);
    printf("\nNumber of Spaces     = %d\n", space);

}

Output

C Program To Count Number of Spaces, Newlines, Tabs and Characters

If you have any compilation errors or doubts in this C Program To Count Number of Spaces, Tabs and Newlines, let us know about in the Comment Section below.

Let's Discuss