Over a million developers have joined DZone.

File Splitter

·

#include
#include

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;
}
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}