home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Interactive Guide / c-cplusplus-interactive-guide.iso / c_ref / csource5 / 359_01 / split.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-10-24  |  1.3 KB  |  73 lines

  1. #include <stdio.h>
  2.  
  3. #include <stdlib.h>
  4.  
  5. #include <fcntl.h>
  6.  
  7.  
  8.  
  9. #ifndef O_BINARY
  10.  
  11. #define O_BINARY 0
  12.  
  13. #endif
  14.  
  15.  
  16.  
  17. usage()
  18.  
  19. {
  20.  
  21.   fprintf(stderr,"Usage: split [inputFile] [chunkSize] [outputBase]\n");
  22.  
  23.   fprintf(stderr, "chunksize is bytes, creates <outputBase>.000, <outputBase>.001, etc\n");
  24.  
  25.   exit(1);
  26.  
  27. }
  28.  
  29.  
  30.  
  31. p_open(ob, p)
  32.  
  33. char *ob;
  34.  
  35. int p;
  36.  
  37. {
  38.  
  39.   char partname[1024];
  40.  
  41.   sprintf(partname, "%s.%03d", ob, p);
  42.  
  43.   return open(partname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0666);
  44.  
  45. }
  46.  
  47.  
  48.  
  49. main(argc, argv)
  50.  
  51. int argc;
  52.  
  53. char **argv;
  54.  
  55. {
  56.  
  57.   char buf[4096];
  58.  
  59.   long chunksize, left, r;
  60.  
  61.   int partnum;
  62.  
  63.   int inf, f;
  64.  
  65.   
  66.  
  67.   if (argc != 4)
  68.  
  69.     usage();
  70.  
  71.  
  72.  
  73.   inf = open(argv[1], O_RDONLY|O_BINARY);
  74.  
  75.   if (inf < 0)
  76.  
  77.     usage();
  78.  
  79.  
  80.  
  81.   chunksize = atol(argv[2]);
  82.  
  83.   if (chunksize < 1)
  84.  
  85.     usage();
  86.  
  87.  
  88.  
  89.   partnum = 0;
  90.  
  91.   left = chunksize;
  92.  
  93.   f = p_open(argv[3], partnum);
  94.  
  95.   while (1)
  96.  
  97.   {
  98.  
  99.     if (left < 4096)
  100.  
  101.       r = read(inf, buf, left);
  102.  
  103.     else
  104.  
  105.       r = read(inf, buf, 4096);
  106.  
  107.     if (r <= 0)
  108.  
  109.     {
  110.  
  111.       close(f);
  112.  
  113.       close(inf);
  114.  
  115.       exit(0);
  116.  
  117.     }
  118.  
  119.     
  120.  
  121.     write(f, buf, r);
  122.  
  123.     left -= r;
  124.  
  125.     
  126.  
  127.     if (left == 0)
  128.  
  129.     {
  130.  
  131.       close(f);
  132.  
  133.       partnum++;
  134.  
  135.       f = p_open(argv[3], partnum);
  136.  
  137.       left = chunksize;
  138.  
  139.     }
  140.  
  141.   }
  142.  
  143. }
  144.  
  145.