Richard Heathfield said:
Well - one could read 8 bytes, and do
fprintf(fpout, "%02X %02X %02X %02X %02X %02X %02X %02X\n",
buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]);
...er, oh yeah, so he can.
Yes, but what about the (likelier) case where the file has a number of
bytes that isn't a multiple of 8? Your original version handled that
easily; the suggested version less so. I'm presuming, possibly
incorrectly, that fprintf() is expensive relative to sprintf(), so
perhaps something like this would be good (criticisms welcome):
#include <stdio.h>
#include <assert.h>
#define BYTES_PER_LINE 8
int main( int argc, char *argv[] )
{
char outbuf[3*BYTES_PER_LINE+1], *bufptr;
int inchar, count=0;
FILE *fpin, *fpout;
assert( argc > 2 );
assert( (fpin = fopen(argv[1],"r")) != NULL );
assert( (fpout = fopen(argv[2],"w")) != NULL );
bufptr = outbuf;
while( (inchar=fgetc(fpin)) != EOF ) {
bufptr += sprintf( bufptr, "%02X ", inchar ); /* assume success */
if( ++count % BYTES_PER_LINE == 0 ) {
*(bufptr-1)='\n';
fputs( outbuf, fpout );
bufptr = outbuf;
}
}
if( bufptr != outbuf ) {
*(bufptr-1)='\n';
fputs( outbuf, fpout );
}
assert( !fclose(fpin) );
assert( !fclose(fpout) );
return 0;
}