by Dinesh Thakur Category: C Programming (Pratical)

In this program user ask to calculate the words in file. User declare the pointer type file variable for value reference. File open function used to open the file for reading the content in file. If condition checks whether the file is null if it is the else condition comes in where while condition checks the logic (ch!=eof). Through else condition the content check to end of file. And then to print the result on display.

Problem statement:- 
This is the program where user will find out the word in the file that is been created.

  1. Create file for content storing.
  2. Using required condition for fulfilling the requirement.
  3. Display the result on screen.

This C program is successfully compiled and run on a System. Output is shown below.

#include<stdio.h>
void main()
{
    FILE *p;
    char ch;
    int w=1;
    clrscr();
    p=fopen("source","r");
    if(p==NULL)
     {
         printf("file not found");
      }
    else
      {
          ch=fgetc(p);
          while(ch!=EOF)
                 {
                        printf("%c",ch);
                        if(ch==' '||ch=='\n')
                          {
                               w++;
                          }
                               ch=fgetc(p);
                 }
                               printf("\nWords in a file are=%d",w);
     }
                              fclose(p);
                              getch();
}

C Program Count the Numbers of Words in a File

Related Articles on C Programming

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content