In the last tutorial I told you about the basic file input output functions. If you are reading this tutorial by skipping the last tutorial then I would strongly recommend you to read that tutorial first. So today I will tell you one program that will count all the characters, spaces, blanks and tabs inside one text file.
File Handling in C
C Program to count characters, spaces, tabs and lines in a text file
Lets straight away write the program first.
#include<stdio.h> void main() { FILE *np; char ch; int lines=1,tabs=0,blanks=0,characters=0; //the last line is not counted so default value of lines is 1 np=fopen("demo.txt","r"); while(ch!=EOF) { ch=fgetc(np); characters++; if(ch==' ') blanks++; if(ch=='n') lines++; if(ch=='t') tabs++ ; } fclose(np); printf("Characters=%d",characters); printf("nSpaces=%d",blanks); printf("nTabs=%d",tabs); printf("nLines=%dn",lines); }
Output
Note: I have opened the demo.txt in my computer. So the output will vary from file to file.
Explanation
1. First of all I have declared one FILE structure pointer np and initialized four integers which are lines, tabs, blanks and characters.
2. After that I have opened the file demo.txt using fopen() function. I have used the same function in my last tutorial too.
3. After that I have started one while loop. Inside it I am fetching the characters of that file using fgetc() function one by one. This while loop will continue till end of file. The end of file is encountered when value of ch become EOF.
5. Now I have used if blocks to count the number of characters, blanks, lines and tabs.
6. At the end of the loop I have closed the file using fclose() function.
7. The I have printed the values inside the integer variables which I have used to count the characters, spaces, blanks and tabs.
Note: This is one of the most frequently used practical application of file input output functions. By introducing some variables inside the program I have used it to count the characters inside the file.
Till now we have seen how to read from file and then display it on console. In our next tutorials we will learn about how to write something into a file.