/* This program changes the byte order in a data file of the form HEADERLENGTH=N\n ... (N Bytes) (4 byte word) (4 byte word) ... The order of the bytes in each of the 4 byte words is reversed. usage: byte_swap input_file output_file [block_size] */ #include #include #include #include void critical(char *message); void main (int argc, char *argv[]) { char *input_file, *output_file, *buffer_in, *buffer_out; long word, hsize, bsize, bytes_read, count; int hflag; FILE *input, *output; if ((argc < 3) || (argc > 5)) { printf ("usage: %s [-nh] input_file output_file [block_size]\n", &argv[0][0]); _exit(1); } if (strcmp(argv[1],"-nh") != 0) hflag = 0; else hflag = 1 ; input_file = argv[1+hflag]; output_file = argv[2+hflag]; if (argc == 4+hflag) { bsize = atoi(argv[3+hflag]); } else { bsize = 1024; } /* open the relevant files */ if ((input = fopen(input_file, "r+b")) == NULL) critical("ERROR: Cannot open input file.\n"); if ((output = fopen(output_file, "r+b")) == NULL) { if ((output = fopen(output_file, "wb")) == NULL) critical("ERROR: Cannot create output file.\n"); } hsize = 0; if (hflag == 0) { if (fscanf (input, "HEADERLENGTH=%li", &hsize) != 1) { critical ("ERROR: Could not find header length, use -nh if no header.\n"); } buffer_in = malloc (hsize); if ( fseek(input, 0, SEEK_SET) != 0) critical("ERROR: Seek error in input.\n"); if ( ( fread(buffer_in ,1 , hsize, input) != hsize) || ferror(input) ) critical ("ERROR: Error reading header.\n"); if ( ( fwrite(buffer_in ,1 , hsize, output) != hsize) || ferror(output) ) critical ("ERROR: Error writing header.\n"); free (buffer_in); } buffer_in = malloc (bsize); buffer_out = malloc (bsize); bytes_read = bsize; for (count = 0; bytes_read == bsize; count++) { if ( fseek(input, hsize + count*bsize, SEEK_SET) != 0) critical("ERROR: Seek error in input.\n"); bytes_read = fread(buffer_in, 1, bsize, input); if ( ferror(input) ) critical ("ERROR: File read error.\n"); for (word = 0; word < (bytes_read/4); word++) { buffer_out [word*4 + 0] = buffer_in [word*4 + 3]; buffer_out [word*4 + 1] = buffer_in [word*4 + 2]; buffer_out [word*4 + 2] = buffer_in [word*4 + 1]; buffer_out [word*4 + 3] = buffer_in [word*4 + 0]; } if (fseek(output, hsize + count*bsize, SEEK_SET) != 0) critical("ERROR: Seek error in output.\n"); if ( (bytes_read != fwrite(buffer_out, 1, bytes_read, output)) || ferror(output) ) critical ("ERROR:File write error.\n"); } if (fclose(output)) critical("ERROR: Cannot close output file.\n"); if (fclose(input)) critical("ERROR: Cannot input output file.\n"); free (buffer_in); free (buffer_out); printf ("%d header bytes copied\n", hsize); printf ("%d bytes reordered\n", count*bsize + bytes_read); } void critical (char *message) { printf("%s",message); _exit(1); }