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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #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

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.