Mercurial > hg > aim92
view tools/swab.c @ 0:5242703e91d3 tip
Initial checkin for AIM92 aimR8.2 (last updated May 1997).
author | tomwalters |
---|---|
date | Fri, 20 May 2011 15:19:45 +0100 |
parents | |
children |
line wrap: on
line source
/* swab.c swap bytes ------ Read and write binary shorts (2-bytes). With no filename arguments, data is expected on the stdin, and the result is written on the stdout. Otherwise each given filename is processed in turn. When the `output' option is "off" output overwrites the respective input file. (The respective output for the stdin is the stdout). Otherwise all results are written to the one given output file (which is the stdout by default). */ #include <stdio.h> #include <math.h> #include "options.h" char applic[] = "Swap byte order of binary 2-byte data." ; static char *helpstr, *outstr, *sizestr ; static Options option[] = { { "help" , "off" , &helpstr , "help" , DEBUG }, { "output" , "stdout" , &outstr , "output filename (off = overwrite input)" , VAL }, { "SIZE" , "262144" , &sizestr , "buffer size in bytes" , SVAL }, ( char * ) 0 } ; int SIZE ; /* size of temp buffer for stdin data */ main(argc, argv) int argc ; char *argv[] ; { FILE *ifp, *ofp ; int i, j, n, doOpen, doCreate ; char *data, *Y ; i = getopts( option, argc, argv ) ; if ( !isoff( helpstr ) ) helpopts( helpstr, argv[0], applic, option ) ; SIZE = atoi( sizestr ) ; doOpen = doCreate = 0 ; if ( i == 0 ) ifp = stdin ; else doOpen++ ; if ( isoff( outstr ) ) { if ( i == 0 ) ofp = stdout ; /* o/p = i/p which is stdin */ else doCreate++ ; /* o/p = i/p for current file */ } else if ( isstr( outstr, "stdout") ) ofp = stdout ; else if ( ( ofp = fopen( outstr, "w" ) ) == (FILE *)0 ) { fprintf( stderr,"swab: can't create %s\n", outstr ) ; exit( 1 ) ; } Y = (char *)malloc( sizeof( short ) ) ; if ( ( data = (char *)malloc( SIZE ) ) == NULL ) { fprintf( stderr, "malloc out of space\n" ) ; exit( 1 ) ; } do { if ( doOpen && ( ifp = fopen( argv[argc-i], "r" ) ) == (FILE *)0 ) { fprintf( stderr,"swab: can't open %s\n", argv[argc-i] ) ; exit( 1 ) ; } for ( n = 0 ; n < SIZE && fread( &data[n], sizeof(short), 1, ifp ) ; n += 2 ) ; if ( n == SIZE ) fprintf( stderr, "warning: buffer out of space, increase SIZE\n" ) ; if ( doOpen ) fclose( ifp ) ; if ( doCreate && ( ofp = fopen( argv[argc-i], "w" ) ) == (FILE *)0 ) { fprintf( stderr,"swab: can't create %s\n", argv[argc-i] ) ; exit( 1 ) ; } for ( j = 0 ; j < n ; j += 2 ) { *Y = data[j+1] ; *(Y+1) = data[j] ; fwrite( Y, sizeof(short), 1, ofp ); } if ( doCreate ) fclose( ofp ) ; } while ( --i > 0 ) ; }