This is a C/C++ language program that can read a text file. This program is takes a filename as command-line argument and then it reads the file line-by-line. The program prints the total number of characters and words in each line. The program also prints total the number of lines in the file. File name and path should be absolute path. You can also give proper relative path including file name. If file is present in the same directory as program, then only file name is required.

#include <stdio.h>

int main (int argc, char *argv[]){
  FILE *fp;
  int nchars, nwords, nlines;
  int lastnblank;    /* 0 iff the last character was a space */
  char c;

  if(argc!=2){
    printf("Usage: %s filenamen", argv[0]);
    exit(0);
  }
  if((fp=fopen(argv[1],"r"))==NULL){
    perror("fopen");
    exit(0);
  }
  nchars=nwords=nlines=lastnblank=0;
  while((c=getc(fp))!=EOF){
    nchars++;
    if (c=='n'){
      if (lastnblank)
 nwords++;
      printf("words=%d, characters=%dn", nwords, nchars);
      nchars=nwords=lastnblank=0;
      nlines++;
    }else{
      if (((c==' ')||(c=='t'))&(lastnblank))
 nwords++;
      lastnblank=((c!=' ')&&(c!='t'));
    }
  }
  printf("lines=%dn", nlines);
  fclose(fp);
}
Tagged with: C/C++ languageProgrammingSource Code
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.