Code:
/* splt.c */
/* splits file into user specified byte parts */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#define BUFSIZE 4096
char *getfilenameout(char *filenamebuf, char *filename, unsigned int suffix);
FILE *open_outfile(char *filenamebuf, char *filename, unsigned int suffix);
void display_usage(void);
int main(int argc, char *argv[])
{
FILE *fp, *outfp, *infout;
char buf[BUFSIZE];
char filenamebuf[100];
char *filenameout;
unsigned int size, parts;
unsigned int suffix = 0;
int i, c;
i = 0;
char *filename = argv[2];
struct stat fl;
struct stat *pt = &fl;
char *endptr = 0;
if (argc != 3) {
display_usage();
exit(1);
}
size = strtoul(argv[1], &endptr, 10);
if (*endptr != 0) {
fprintf(stderr, "splt: not a valid decimal number.\n");
exit(1);
}
if (size < 1) {
fprintf(stderr, "splt: size must be at least 1 byte.\n");
exit(1);
}
/* open file to splt */
if ( (fp = fopen(argv[2], "rb")) == NULL) {
fprintf(stderr, "splt: %s: ", argv[2]);
perror("");
exit(1);
}
/* get file size */
stat(argv[2], pt);
/* make sure size of file / specified split size will fit into 1000 parts */
if ( (parts = pt->st_size / size) > 1000) {
fprintf(stderr, "splt: split would require greater than 1000 parts.\n");
exit(1);
}
/* save info on split to inf file (file.001) */
infout = open_outfile(filenamebuf, filename, suffix++);
fprintf(infout, "%s\n", argv[2]);
outfp = open_outfile(filenamebuf, filename, suffix++);
printf("creating %s\n", filenamebuf);
fprintf(infout, "%s\n", filenamebuf);
/* main splt loop */
while ( (c = fgetc(fp)) != EOF) {
if (i == size) {
fclose(outfp);
i = 0;
outfp = open_outfile(filenamebuf, filename, suffix++);
printf("creating %s\n", filenamebuf);
fprintf(infout, "%s\n", filenamebuf);
}
fputc(c, outfp);
i++;
}
fclose(fp);
fclose(outfp);
fclose(infout);
return 0;
}
char *getfilenameout(char *filenamebuf, char *filename, unsigned int suffix)
{
sprintf(filenamebuf, "%s.%03d", filename, suffix);
return filenamebuf;
}
FILE *open_outfile(char *filenamebuf, char *filename, unsigned int suffix)
{
char *filenameout;
FILE *outfp;
filenameout = getfilenameout(filenamebuf, filename, suffix);
outfp = fopen(filenameout, "wb");
return outfp;
}
void display_usage(void)
{
fprintf(stderr, "Usage: splt [size in bytes] file.\n");
}