DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

File Splitter

02.09.2006
| 235 views |
  • submit to reddit
        
#include<stdio.h>
#include<stdlib.h>

void usage(const char *message)
{
   if(message) puts(message);
   puts("Usage: FileSplitter inputfile [bytes (default 1000000)]");
   exit(1);
}

int main(int argc, const char *argv[])
{
   FILE *in, *out = NULL;
   long count=0, max = 1000000;
   int filecount = 0;

   if(argc < 2 || argc > 3) usage(NULL);
   in = fopen(argv[1], "rb");
   if(in == NULL) usage("Could not open inputfile.");
   if(argc == 3)
   {
      max = atol(argv[2]);
      if(max <= 0) usage("Could not parse bytes argument.");
   }

   while(max)
   {
      char buf[256];
      sprintf(buf, "%s%02d", argv[1], ++filecount);
      puts(buf);

      out = fopen(buf, "wb");
      for(count=0; count < max; ++count)
      {
         int i = getc(in);
         if(i == -1)
         {
            max = 0; /* to break outer loop */
            break;
         }
         putc(i, out);
      }
      fflush(out);
      fclose(out);
   }
   return 0;
}
    
    Tags:
  • C