home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_300 / 359_01 / split.c < prev    next >
C/C++ Source or Header  |  1991-10-24  |  1KB  |  73 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4.  
  5. #ifndef O_BINARY
  6. #define O_BINARY 0
  7. #endif
  8.  
  9. usage()
  10. {
  11.   fprintf(stderr,"Usage: split [inputFile] [chunkSize] [outputBase]\n");
  12.   fprintf(stderr, "chunksize is bytes, creates <outputBase>.000, <outputBase>.001, etc\n");
  13.   exit(1);
  14. }
  15.  
  16. p_open(ob, p)
  17. char *ob;
  18. int p;
  19. {
  20.   char partname[1024];
  21.   sprintf(partname, "%s.%03d", ob, p);
  22.   return open(partname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0666);
  23. }
  24.  
  25. main(argc, argv)
  26. int argc;
  27. char **argv;
  28. {
  29.   char buf[4096];
  30.   long chunksize, left, r;
  31.   int partnum;
  32.   int inf, f;
  33.   
  34.   if (argc != 4)
  35.     usage();
  36.  
  37.   inf = open(argv[1], O_RDONLY|O_BINARY);
  38.   if (inf < 0)
  39.     usage();
  40.  
  41.   chunksize = atol(argv[2]);
  42.   if (chunksize < 1)
  43.     usage();
  44.  
  45.   partnum = 0;
  46.   left = chunksize;
  47.   f = p_open(argv[3], partnum);
  48.   while (1)
  49.   {
  50.     if (left < 4096)
  51.       r = read(inf, buf, left);
  52.     else
  53.       r = read(inf, buf, 4096);
  54.     if (r <= 0)
  55.     {
  56.       close(f);
  57.       close(inf);
  58.       exit(0);
  59.     }
  60.     
  61.     write(f, buf, r);
  62.     left -= r;
  63.     
  64.     if (left == 0)
  65.     {
  66.       close(f);
  67.       partnum++;
  68.       f = p_open(argv[3], partnum);
  69.       left = chunksize;
  70.     }
  71.   }
  72. }
  73.