Reading Files

This is a small C language program that can read a text file. The program is given file name as command parameter and it reads the file line by line. The program will print out number of characters and words in each line. The program will also print out the number of lines in the text file. File name should contain complete physical path or only the file name if file is present in the same directory as program.

/*******************************************************
*     MYCPLUS Sample Code - http://www.mycplus.com     *
*                                                     *
*   This code is made available as a service to our   *
*      visitors and is provided strictly for the      *
*               purpose of illustration.              *
*                                                     *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/

#include 

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);
}

Leave a Reply