In this tutorial you will learn about the C Program to count Characters, Spaces, Tabs, Newline in a File and its application with practical example.
C Program to count Characters, Spaces, Tabs, Newline in a File
In this tutorial, you will learn about the C Program to count Characters, Spaces, Tabs, Newline in the File with a practical example.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Concepts of while loop.
- Conditional Statements in C programming.
- Using file functions of c language.
Count Characters, Spaces, Tabs, Newline in a File
As we all know the String is a collection of character data types. In strings, only one variable is declared which can store multiple values. First will take the string from the user. Then will pass that string to a for loop for copying. The C programming language has many pre-defined functions for string manipulation. but in today’s tutorial, we will count Characters, Spaces, Tabs, Newline in a File.
With the help of this program, we can count Characters, Spaces, Tabs, Newline in a File
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
1. Declaring the variables for the program. 2. Taking the input file from the user. 3. Reading the file. 4. Counting the Data in the files. 5. Printing the results. 6. End program. |
Program:-
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> int main() { //declaraiton of variables FILE *fp; char ch, fname[30]; int noOfChar=0, noOfSpace=0, noOfTab=0, noOfNewline=0; //Taking the input from the user printf("Enter file name with extension: "); gets(fname); //opening file fp = fopen(fname, "r"); //reading characters from file while(fp) { ch = fgetc(fp); if(ch==EOF) break; noOfChar++; if(ch==' ') noOfSpace++; if(ch=='\t') noOfTab++; if(ch=='\n') noOfNewline++; } fclose(fp); //printing the number of characters, spaces, tabs, newLine printf("\nNumber of characters = %d", noOfChar); printf("\nNumber of spaces = %d", noOfSpace); printf("\nNumber of tabs = %d", noOfTab); printf("\nNumber of newline = %d", noOfNewline); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- *fp[100] = it will hold the address value.
- ch = it will hold the character value.
- fname[30] = it will hold the string value of the file name.
- noOFChar = it will hold the string value of the file name.
- noOFSpaces = it will hold the string value of the file name.
- noOFTab = it will hold the string value of the file name.
- noOFNewline = it will hold the string value of the file name.
Taking Input string from the user.
Reading the file.
Counting the characters, spaces, tabs, newline.
Printing output data.