- C Programming Examples
- C Programming Examples
- C Print Hello World
- C Get Input from User
- C Print Integer
- C Add Two Numbers
- C Add Subtract Multiply Divide
- C Add n Numbers
- C Area Perimeter of Square
- C Area Perimeter of Rectangle
- C Area Circum of Circle
- C Fahrenheit to Celsius
- C Celsius to Fahrenheit
- C Inches to Centimeters
- C Kilogram to Gram
- C Reverse a Number
- C Swap Two Numbers
- C Interchange Numbers
- C Print ASCII Value
- C Print Fibonacci Series
- C Check Palindrome or Not
- C Check Armstrong or Not
- C Find Armstrong Numbers
- C Find nCr and nPr
- C Find Profit Loss
- C Sum of their Square
- C First & Last Digit Sum
- C Sum of All Digit
- C Product of All Digit
- C Print Total Digit in Number
- C Check Perfect Number
- C Find Basic Gross Salary
- C Round Number to Integer
- C Print Series upto n Term
- C Find Factors of Number
- C if-else & Loop Programs
- C Check Even or Odd
- C Check Prime or Not
- C Check Alphabet or Not
- C Check Vowel or Not
- C Check Leap Year or Not
- C Is Reverse Equal Original
- C Make Calculator
- C Add Digits of Number
- Count Positive Negative Zero
- C Largest of Two Numbers
- C Largest of Three Numbers
- C Smallest of Two Numbers
- C Smallest of Three Numbers
- C Find Factorial of Number
- C Find LCM & HCF
- C Find LCM of n Numbers
- C Find HCF of n Numbers
- C Find Arithmetic Mean
- C Find Average, Percentage
- C Find Student Grade
- C Print Table of Number
- C Print Prime Numbers
- C Find Discount Purchase
- C Calculate Parcel Charge
- C Calculate Wage of Labor
- C Print Phone Bill
- C Conversion programs
- C Decimal to Binary
- C Decimal to Octal
- C Decimal to Hexadecimal
- C Binary to Decimal
- C Binary to Octal
- C Binary to Hexadecimal
- C Octal to Decimal
- C Octal to Binary
- C Octal to Hexadecimal
- C Hexadecimal to Decimal
- C Hexadecimal to Binary
- C Hexadecimal to Octal
- C Pattern Programs
- C Pattern Printing Programs
- C Print Diamond Pattern
- C Print Floyd's Triangle
- C Print Pascal's Triangle
- C Array Programs
- C 1D Array Programs
- C Linear Search
- C Binary Search
- C Largest Element in Array
- C Smallest Element in Array
- C Second Largest/Smallest
- C Count Even Odd
- C Array Element at Even
- C Array Element at Odd
- C Print Even Array Elements
- C Print Odd Array Elements
- C Sum/Product of Even/Odd
- C Reverse an Array
- C Insert Element in Array
- C Delete Element from Array
- C Merge Two Arrays
- C Bubble Sort
- C Selection Sort
- C Insertion Sort
- C Print Common Elements
- C 2D Array Programs
- C Add Two Matrices
- C Subtract Two Matrices
- C Transpose a Matrix
- C Multiply Two Matrices
- C Sum All Matrix Elements
- C Largest Element in Matrix
- C Print Row Column Total
- C 3D Array Programs
- C String Programs
- C Print String
- C Find Length of String
- C Compare Two String
- C Copy a String
- C Concatenate String
- C Reverse a String
- C Count Vowels Consonants
- C Replace Vowel in String
- C Delete Vowels from String
- C Delete Word from String
- C Frequency of Character
- C Count Word in String
- C Remove Spaces from String
- C Sort a String
- C Sort String in Alphabetical
- C Sort Words in Ascending
- C Sort Words in Descending
- C Uppercase to Lowercase
- C Lowercase to Uppercase
- C Swap Two Strings
- C Check Anagram or Not
- C Check Palindrome String
- C Print Number in Words
- C Print Successive Character
- C Character without Space
- C File Programs
- C Read a File
- C Write Content to File
- C Read & Display File
- C Copy a File
- C Merge Two Files
- C Reverse File
- C Count All Character in File
- C List Files in Directory
- C Encrypt & Decrypt a File
- C Delete a File
- C Misc Programs
- Generate Random Numbers
- C Print Date Time
- C Print Message with Time
- C Get IP Address
- C Print Smiling face
- C Pass Array to Function
- Add Two Numbers using Pointer
- C Address of Variable
- C Shutdown Computer
- C Programming Tutorial
- C Tutorial
C program to count characters, spaces, tabs, and newlines in a file
Before starting to write a program in C that counts the total number of characters, spaces, tabs, and newlines present in any file inside the current directory. Here "current directory" means the directory where your C program files are getting saved.
Now let's create a text file named fresherearth.txt and write the following line:
hello everyone i am a file this is fresherearth there are total of 4 lines present here
Now put this file inside the current directory.
Here's a screenshot of the file fresherearth.txt, which contains all of the above text (four lines). In this screenshot, you can also see that the file is saved inside the current directory:
Now here is the program that counts characters, spaces, tabs, and newlines present inside the file that was created earlier, named fresherearth.txt. You can also create any file and count these things for that file. Or you can also enter any filename that already exists inside the current directory:
#include<stdio.h> #include<conio.h> int main() { FILE *fp; char ch, fname[30]; int noOfChar=0, noOfSpace=0, noOfTab=0, noOfNewline=0; printf("Enter file name with extension: "); gets(fname); fp = fopen(fname, "r"); while(fp) { ch = fgetc(fp); if(ch==EOF) break; noOfChar++; if(ch==' ') noOfSpace++; if(ch=='\t') noOfTab++; if(ch=='\n') noOfNewline++; } fclose(fp); printf("\nNumber of characters = %d", noOfChar); printf("\nNumber of spaces = %d", noOfSpace); printf("\nNumber of tabs = %d", noOfTab); printf("\nNumber of newline = %d", noOfNewline); getch(); return 0; }
As the above program is written in the Code::Blocks IDE, here is the sample run after it has been successfully built and run. This is the first screenshot:
Now enter the name of that file with the appropriate extension that has been created in the current directory and press the enter key. If you will also create the same file with the same content, then here is the second screenshot of the sample run that you will also get on your output screen:
As you can see, the program shows the total number of characters, spaces, tabs, and newlines present in the file fresherearth.txt.
You can also type the name of the file in which your current program is written. In my case, the name of the program is 21.c. Let's type 21.c. and find out what will happen:
As you can see, the program also prints the total number of characters, tabs, spaces, and newlines present inside the program that you have written and saved.
Note: Before typing your current program name as a filename, be sure that you have saved your program.
Here are some of the main steps used in the above program:
- Get the file name as input from the user at run-time. Always ask the user to enter the filename along with its extension, say, fresherearth.txt. Here ".txt" is the extension of the file.
- Open that file with the fopen() function to read the content contained within it.
- Create a while loop and run this loop until the file pointer goes to the end of the file.
- Get the character from the file using the fgetc() function and initialize it to the ch variable.
- Check whether ch is equal to the end of the file; if it is, then break out of the loop; otherwise, continue to the next statement.
- First, increment the value of the variable that is responsible for character counting. Because everything inside the file is character.
- And then check whether the character variable is equal to space; if it is, then increment the value of the variable that is responsible for space counting.
- In a similar way, increment the value of the tab and newline counting variables, if found.
- In this way, you have a total of four variables, namely, noOfChar, noOfSpace, noOfTab, and noOfNewline.
- All these four variables hold the total number of characters, spaces, tabs, and newlines present inside the given file.
- After breaking out of the loop, never forget to close the file pointer using the fclose() function.
- Finally, print out the value of all four variables.
You can also add some more lines of coding to count extra things like vowels, numbers, etc. Let's create another program with some extra lines of code along with its sample run. The question is: write a program in C to count the following things inside any file entered by the user at run-time:
- Total Number of Characters
- Total Number of Spaces
- Total Number of Tabs
- Total Number NewLines
- Total Number Vowels
- Total Number of Consonants
- Total Number of Numbers
The program given below is the answer to this question.
#include<stdio.h> #include<conio.h> int main() { FILE *fp; char ch, fname[30]; int noOfChar=0, noOfSpace=0, noOfTab=0, noOfNewline=0; int noOfVowel=0, noOfConsonant=0, noOfNumber=0; printf("Enter file name with extension: "); gets(fname); fp = fopen(fname, "r"); while(fp) { ch = fgetc(fp); if(ch==EOF) break; noOfChar++; if(ch>=65 && ch<=90) { noOfConsonant++; if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') noOfVowel++; } if(ch>=97 && ch<=122) { noOfConsonant++; if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u') noOfVowel++; } if(ch>=48 && ch<=57) noOfNumber++; if(ch==' ') noOfSpace++; if(ch=='\t') noOfTab++; if(ch=='\n') noOfNewline++; } fclose(fp); printf("\nTotal Number of Characters = %d", noOfChar); printf("\nTotal Number of Spaces = %d", noOfSpace); printf("\nTotal Number of Tabs = %d", noOfTab); printf("\nTotal Number NewLines = %d", noOfNewline); printf("\nTotal Number Vowels = %d", noOfVowel); printf("\nTotal Number of Consonants = %d", noOfConsonant); printf("\nTotal Number of Numbers = %d", noOfNumber); getch(); return 0; }
After successfully building and running, here is the first screenshot of the sample run of the above program:
Now enter any file name. Let's enter the current filename, where we have written and saved our current program, which is test.c in this case, and press the ENTER key to see the following output:
« Previous Program Next Program »