#include #define BUFSIZE 1024 * 1024 FILE *outfile; FILE *infile; unsigned char inbuf[BUFSIZE]; main( int argc, char **argv ) { int i; /* check that there are at least 3 input arguments */ if (argc < 3) { fprintf(stderr, "%s: Need at least 2 input arguments!\n", argv[0] ); fprintf(stderr, "Usage: %s file1 file2 [ file3 [ file 4 [.... fileN ] fileout.\n", argv[0] ); fprintf(stderr, " \t\t bcat concatonates two or more binary files and writes the output to the last filename in the list\n"); fprintf(stderr, " \t\t if the last file name exists and is not empty return an error\n"); exit(1); } /* check that we can open output file */ if ( NULL == (outfile = fopen(argv[argc-1], "ab")) ) { fprintf(stderr, "ERROR %s: cannot open output file for writing, %s\n", argv[0], argv[argc-1]); exit(1); } /* check that output file is empty */ fseek(outfile, 0, SEEK_END); if ( ftell(outfile) > 0 ) { fprintf(stderr, "ERROR %s: output file, %s, is not empty\n", argv[0], argv[argc-1]); exit(1); } i = 1; /* loop through input files, copying data to output file. */ while( i < argc - 1 ) { if ( NULL == (infile = fopen(argv[i], "r")) ) { fprintf(stderr, "WARNING %s: cannot open input file, %s\n", argv[0], argv[i]); } else { long inbytes, writtenBytes; while ( 0 < (inbytes = fread( inbuf, 1, BUFSIZE, infile )) ) { if ( inbytes > (writtenBytes = fwrite( inbuf, 1, inbytes, outfile ) )) { fprintf(stderr, "WARNING %s: error writing data to output file, %s\n", argv[0], argv[i]); } } fclose(infile); } i++; } fclose(outfile); }