//---------------------------------------------------------------- // dump.cpp // // Dumps a specified file in hexadecimal and ascii formats. // // programmer: ALLAN CRUSE // written on: 18 JAN 2003 //---------------------------------------------------------------- #include // for printf(), perror() #include // for open(), O_RDONLY #include // for lseek(), close() #include // for exit() #include // for mmap(), munmap() int main( int argc, char *argv[] ) { // check for mandatory command-line argument if ( argc == 1 ) { printf( "You must specify an input-file\n" ); exit(1); } // map the specified input-file to user's address-space int fd = open( argv[1], O_RDONLY ); if ( fd < 0 ) { perror( "open" ); exit(1); } int filesize = lseek( fd, 0, SEEK_END ); void *in = mmap( NULL, filesize, PROT_READ, MAP_PRIVATE, fd, 0 ); if ( in == (void*)(-1) ) { perror( "mmap" ); exit(1); } close( fd ); // display title for the screen output printf( "\nFILE DUMP: %s (%d bytes)\n", argv[1], filesize ); // main loop to display hex and ascii dump unsigned char *cp = (unsigned char*)in; for (int i = 0; i < filesize; i += 16) { int j; printf( "\n%08X: ", i ); for (j = 0; j < 16; j++) { if ( i+j < filesize ) printf( "%02X ", cp[i+j] ); else printf( " " ); } printf( " " ); for (j = 0; j < 16; j++) { unsigned char ch = (i+j < filesize) ? cp[i+j] : ' '; if (( ch < 0x20 )||( ch > 0x7E )) ch = '.'; printf( "%c", ch ); } } printf( "\n\n" ); // unmap the memory-mapped input-file munmap( in, filesize ); }