Program listing for simulating the cat command in UNIX with error handling

#include <stdio.h>
 #include <process.h>
 
 void copyfile(FILE *,FILE *);
 
 int main(int argc, char *argv[])
 {
     FILE *fileptr, *fopen();
 
     if(argc>1)
         while(--argc>0)
             if((fileptr=fopen(*++argv, "r"))==NULL)
             {
                 fprintf(stderr,"cat : can't open %sn",*argv);
                 exit(1);
             }
             else{
                  copyfile(fileptr,stdout);
                  fclose(fileptr);
             }
     else
         copyfile(stdin, stdout);
     if(ferror(stdout))
     {
         fprintf(stderr, "cat : error in writing at stdoutn" );
         exit(2);
     }
     return(0);
 }
 /* Function to copy file from rfp to wfp */
 void copyfile(FILE *rfp, FILE *wfp)
 {
     int c;
 
     while((c=fgetc(rfp))!=EOF)
            fputc(c, wfp);
     return;
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.