A little help on C with file handling

Asked By 0 points N/A Posted on -
qa-featured

Hi i want to read the contents of a file and then count the number of words it has. Then the program should automatically generate a file. I'm new to C please help

SHARE
Best Answer by Hoting Gracia
Answered By 0 points N/A #89208

A little help on C with file handling

qa-featured

 

Please let me know if you have any problems in this program.
 
 
 
 
//Program to count the number of words in an input text file
 
#define NULL 0
FILE *fpt;
void main()
{
 
 char name[20],c;
 int nw=0;
 clrscr();
 printf("Enter the name of file to be checked:-  ");
 gets(name);
 fpt=fopen(name,"r");
 if (fpt==NULL)
 {
  printf("
ERROR – can/'t open file %s",name);
  getch();
  exit(0);
 }
 else
 {
 while ((c=getc(fpt))!=EOF)
 {
  switch(1)
  {
   case 1:
 if (c==' ')
 {
   point: // do
 //    nw=nw+1-1;
  while((c=getc(fpt))==' ');
 
  if (c!=' ')
nw=nw+1;
  if(c=='
')nw–;
 }
 
 
 //  case 3:
 if(c=='
'){
   goto point;}
 
  }
 }
 }
 printf("
 
The no. of words in %s is %d.  ",name,nw);
 getch();
}
 
Best Answer
Best Answer
Answered By 5 points N/A #89210

A little help on C with file handling

qa-featured

Hello Genelyn C is the programming Language developed by Dennis Ritchie and now it is the basic for any programming language as major benefits are only with C language and are many programs are developed based on this language as the first priority.

Remember one thing that for any program logic will be same but the implementation will be differed from one language to another language as the syntax and other declarations differs.

The program you required may be used in 2 logic using for and while loop but as a beginner its better use for loop for less confusion as follows…

#include<stdio.h> 

main()

{

long c;

for(c=0;getchar()!=EOF;++c)

print("%ldn",c);

}

Coming to the program Header file is followed by the main method(main()) and declaration of long is done by giving the variable c and most important for loop syntax is " for(initialization;Condition;pre increment) " as used same in the above program.

Hope the solution for your query has been resolved and its better to practice that reduce the lines of code as many as possible to avoid confusion.

Thank You.

 

Related Questions