Gary wrote:[color=blue]
>
> OK, at the risk of drawing ire, here's my "C" code entry in solution
> of this problem. Can it be made more straightforward in C++?[/color]
Well. At least it can be made correct in C :-)
feof returns true only until you have tried AND failed to read past
the end of file.
Thus whenever you see a loop:
while( !feof( ... ) {
// read from file
// do something with the thing read
}
you know immediatly that this will not work correctly
in all circumstances (usually the last thing read from the file
will be processed twice)
feof is meant to be used *after* the reading loop has terminated
to figure out *why* the loop has termineted. If it was because of
eof, then everything is correct, the file has been read completely.
Note that getc (as well as fgetc) returns an int and not a char!!!! This is
important because getc and fgetc need a way to tell the caller: EOF reached
or some other error condition, stop reading from the file.
The following uses this. It is based on what you had:
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
int Byte;
FILE* BinFile;
int ii,i;
if( argc != 2 )
{
printf( "Usage: DumpBin <FileName>\n" );
return EXIT_FAILURE;
}
BinFile = fopen( argv[1], "rb" );
if( !BinFile )
{
printf( "Error: Failed to open file: '%s'\n", argv[1] );
return EXIT_FAILURE;
}
printf( "char %s[] = \n{\n", argv[1] );
i = 0;
while( ( Byte = fgetc( BinFile ) ) != EOF )
{
if( (i % 88) == 0 )
{
printf("\n/* ");
for(ii = 0; ii < 8; ii++)
printf("[%04x]",i + ii);
printf("*/");
}
if((i % 8) == 0)
printf("\n/*[%04x]*/ ",i);
i++;
printf( "0x%02x, ", Byte );
}
if( !feof( BinFile ) )
{
printf( "Error: Reding from file: '%s'\n", argv[1] );
printf( " Could read %d bytes before failure\n", i );
fclose( BinFile );
return EXIT_FAILURE;
}
printf("\n};\n");
fclose( BinFile );
return EXIT_SUCCESS;
}
--
Karl Heinz Buchegger
kbuchegg@gascad.at