Write a program to implement following UNIX commands.

Write a program to implement following UNIX commands.


  • wc -c <filename> displays number of characters for the given file.
  • wc -w <filename> display number of words for given file.
  • wc -l <filename> display number of line for given file.


Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(){
 setbuf(stdout,NULL);
 FILE *fp;
 char s[80],a[5],c[5],temp[100],f[50],p[50],ch;
 int n;
 while(1){
  printf("\nAP:>");
  gets(s);
  if(strcmp(s,"exit")==0){
   exit(0);
  }
  sscanf(s,"%s%s%s",&c,&a,&f);
  fp=fopen(f,"r");
  if(strcmp(c,"wc")!=0){
   printf("Invalid Command.");
  }else if(fp==NULL){
   printf("File cannot be found.");
  }else if(strcmp(a,"-c")==0){
   n=0;
   while(!feof(fp)){
    ch = fgetc(fp);
    n++;
   }
   printf("\nNumber of character present in file:%d",n);
  }else if(strcmp(a,"-l")==0){
   n=0;
   while(!feof(fp)){
    ch=fgetc(fp);
    if(ch==' ' || ch=='\n'){
     n++;
    }
   }
   printf("\nNumber of words present in file:%d",n);
  }else if(strcmp(a,"-l")==0){
   n=0;
   while(!feof(fp)){
    ch=fgetc(fp);
    if(ch=='\n'){
     n++;
    }
   }
   printf("\nNumber of lines present in file:%d",n);
  }
 }
}

Post a Comment

Previous Post Next Post