---
# System prepended metadata

title: PID-1188

---

## Write a program to count characters, spaces, tabs, and newlines in a file.


Now let's create a text file named codes.txt and write the following lines in it and save it:

:::info
hello	everyone
i am	a file \
this is codes
there are total of 4 lines present here
:::

Now here is the program that counts characters, spaces, tabs, and newlines present inside the file that was created earlier, named codes.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.

### **code:**

``` c
#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;
}

```

This program shows the total number of characters, spaces, tabs, and newlines present in the file.


:::spoiler How it works?
-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 the loop;otherwise ,continue to the  next statement.
-Increment the value of the variable that is responsible for character counting.
-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 this way,you have a total of four variables namly,noOfChar,noOfSpace,noOfTab,noOfNewline.
-data manupulation concreate setup data automation.

:::



