Advertisement
DanFloyd

Mycat

May 11th, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9.  
  10. #define BUF_LIMIT 512
  11.  
  12. #define ec_meno1(s,m) \
  13. if ( (s) == -1 ) {perror(m);}
  14.  
  15. int main( int argc, char *argv[] ){
  16.  
  17.     char *optstring = "o:";
  18.     char buf[BUF_LIMIT];
  19.     int opttype, i, l, j, fdin, fdout = STDOUT_FILENO, oflag=0;
  20.  
  21.     opterr = 0;
  22.  
  23.     if(argc < 2){
  24.         printf("Syntax : mycat file1 ... file N [OPTIONS]\n");
  25.         printf("Prints the content of file1 on stdout\n");
  26.         printf("Option: -o fileout\n");
  27.         printf("Prints the content of the input files on the specified output file\n");
  28.         exit(-1);
  29.     }
  30.    
  31.     while((opttype=getopt(argc,argv,optstring)) != -1)
  32.         switch(opttype){
  33.             case 'o' :
  34.                 ec_meno1((fdout = open(optarg,O_WRONLY|O_CREAT|O_APPEND)),"Couldn't open/create the output file");
  35.                 oflag=1;
  36.                 break;
  37.             case '?' :
  38.                 if(optopt == 'o') printf("Option -o requires an argument\n");
  39.                 else printf("Illegal option\n");
  40.                 exit(-1);
  41.             default :
  42.                 printf("Unknown error\n");
  43.                 exit(-1);
  44.         };
  45.  
  46.     if(!oflag) j=1;
  47.     else j=optind;
  48.     for(i=j;i<argc;i++){
  49.         printf("**********************\n");
  50.         printf("Reading %s \n",argv[i]);
  51.         printf("**********************\n");
  52.         ec_meno1((fdin = open(argv[i],O_RDONLY)),"Couldn't open the file");
  53.         while((l = read(fdin,buf,BUF_LIMIT))>0) ec_meno1((write(fdout,buf,l)),"Problem with the output file descriptor");
  54.         ec_meno1(l,"Couldn't read the file");
  55.             ec_meno1((close(fdin)),"Couldn't close the file");
  56.         printf("\n");
  57.     }
  58.     if(oflag) ec_meno1((close(fdout)),"Couldn't close the file");;
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement