home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / magazine / drdobbs / c_spec / execute / cat.c < prev    next >
C/C++ Source or Header  |  1986-02-20  |  2KB  |  73 lines

  1. #include <stdio.h>
  2. #include <fcntl.h>
  3.  
  4. /*    CAT.C        Unlike the cat in K&R, this version grabs the
  5.  *            biggest buffer it can from malloc, copies as
  6.  *            much of the source file as it can with read().
  7.  *            and writes to standard output with write().
  8.  *            Files are opened in binary mode.
  9.  *
  10.  *    Copyright (C) 1985, Allen I. Holub. All rights reserved.
  11.  *
  12.  *    Usage:    cat file...
  13.  *
  14.  *    Exit status: The number of listed files that couldn't be opened
  15.  *             successfully (0 if none).
  16.  */
  17.  
  18. extern int    open    (char*,int);
  19. extern int    read    (int, char*, unsigned);
  20. extern int    write    (int, char*, int);
  21. extern char    *malloc    (unsigned);
  22.  
  23. #define E(x)    fprintf(stderr, "%s\n" ,x)
  24.  
  25. main(argc, argv)
  26. char    **argv;
  27. {
  28.     char        *buf;
  29.     int        src_file ;
  30.     unsigned     bsize = (1024 * 64) - 1 ;
  31.     register int    rval = 0;
  32.     register int    got;
  33.  
  34.     ctlc();
  35.     reargv(&argc, &argv);
  36.  
  37.     if( argc == 1 )
  38.         while( (got = getchar()) != EOF )
  39.             putchar( got );
  40.     else
  41.     {
  42.         if( argv[1][0] == '-' )
  43.         {
  44.             E("CAT:  Copyright (c) 1986, Allen I. Holub\n");
  45.             E("Usage: cat <file list>\n");
  46.             E("Prints all files in list to standard output. Can be");
  47.             E("used to concatanate files by redirecting output ");
  48.             E("to another file, thus the name.");
  49.             exit( 0 );
  50.         }
  51.  
  52.         while( !( buf = malloc(bsize)) && bsize >0  )
  53.             bsize -= 1024 ;
  54.  
  55.         while( --argc > 0 )
  56.         {
  57.             if( (src_file = open(*++argv, O_RDONLY | O_TEXT)) == -1)
  58.             {
  59.                 fprintf(stderr, "cat: can't open %s\n", *argv );
  60.                 rval++;
  61.                 continue;
  62.             }
  63.         
  64.             while( (got = read(src_file, buf, bsize)) != 0 )
  65.                 write( 1, buf, got );
  66.         }
  67.     }
  68.  
  69.     putchar('\n');
  70.  
  71.     exit(rval);
  72. }
  73.