File Handling in C – Part 2

Read: File Handling in C – Part 1

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. 


File Handling in C - Part 2

Note: I have opened the demo.txt in my computer. So the output will vary from file to file.

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.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.