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 prints out number of characters and words in each line. The program will also prints 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 executable.

/*******************************************************
*     MYCPLUS Sample Code - https://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);
}
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post