9
Afficher le contenu d'un fichier en hexadécimal
- #include "dump.h"
- #include <ctype.h>
- #include <unistd.h>
- void dump( unsigned char *buf, int size, FILE *fout ) {
- register int n, i, col = 0;
- const int ncols = 16;
- unsigned char c[ 16 ];
- for( n = 0; n < size; n++ ) {
- fprintf( fout, "%02x ", buf[ n ] );
- c[ col ] = buf[ n ];
- col++;
- if( col == ncols / 2 )
- fprintf( fout, " " );
- else if( col == ncols ) {
- for( i = 0; i < col; i++ )
- fprintf( fout, "%c", isprint(c[ i ] ) ? c[ i ] : '.' );
- fprintf( fout, "\n" );
- col = 0;
- }
- }
- if( col != 0 ) {
- for( i = ncols - col; i > 0; i-- )
- fprintf( fout, " " );
- if( col < ncols / 2 )
- fprintf( fout, " " );
- for( i = 0; i < col; i++ )
- fprintf( fout, "%c", isprint( c[ i ] ) ? c[ i ] : '.' );
- fprintf( fout, "\n" );
- }
- }
- #if defined( STANDALONE )
- #if 0
- #include <io.h>
- #endif
- #include <fcntl.h>
- #include <errno.h>
- #include <string.h>
- #include <stdlib.h>
- int main( int argc, char *argv[] ) {
- unsigned char buf[ 4096 ];
- int n;
- int fd = 0; /* default to stdin */
- switch( argc ) {
- case 1:
- break;
- case 2:
- fd = open( argv[ 1 ], O_RDONLY );
- if ( fd == -1) {
- fprintf( stderr, "%s\n", strerror( errno ) );
- exit( 2 );
- }
- break;
- default:
- fprintf( stderr, "%s [file]\n", argv[0] );
- exit(1);
- }
- while ( (n = read( fd, buf, sizeof( buf ))) != 0 )
- dump( buf, n, stdout );
- exit( 0 );
- }
- #endif
$ gcc -DSTANDALONE -o dump dump.c
$ ./dump < dump.c
23 69 6e 63 6c 75 64 65 20 22 64 75 6d 70 2e 68 #include "dump.h
22 0a 0a 23 69 6e 63 6c 75 64 65 20 3c 63 74 79 "..#include <cty
70 65 2e 68 3e 0a 23 69 6e 63 6c 75 64 65 20 3c pe.h>.#include <
75 6e 69 73 74 64 2e 68 3e 0a 0a 76 6f 69 64 20 unistd.h>..void
64 75 6d 70 28 20 75 6e 73 69 67 6e 65 64 20 63 dump( unsigned c
68 61 72 20 2a 62 75 66 2c 20 69 6e 74 20 73 69 har *buf, int si
7a 65 2c 20 46 49 4c 45 20 2a 66 6f 75 74 20 29 ze, FILE *fout )
...
Commentaires