4

Memory dump

  1. extern void dump( unsigned char *buf, size_t size, FILE *stream );
  1. void dump( unsigned char *buf, size_t size, FILE *stream ) {
  2.     register int n, i, col = 0, line = 0;
  3.  
  4.     const int ncols = 16;
  5.     unsigned char c[ 16 ];
  6.  
  7.     for ( n = 0; n < size; n++ ) {
  8.         if ( col == 0 ) {
  9.             fprintf( stream, "%04d ", line * ncols );
  10.             line++;
  11.         }
  12.         fprintf( stream, "%02x ", buf[ n ] );
  13.         c[ col ] = buf[ n ];
  14.         col++;
  15.         if ( col == ncols / 2 )
  16.             fprintf( stream, " " );
  17.         else if ( col == ncols ) {
  18.             for ( i = 0; i < col; i++ )
  19.                 fprintf( stream, "%c", isprint(c[ i ] ) ? c[ i ] : '.' );
  20.             fprintf( stream, "\n" );
  21.             col = 0;
  22.         }
  23.     }
  24.     if ( col != 0 ) {
  25.         for ( i = ncols - col; i > 0; i-- )
  26.             fprintf( stream, "   " );
  27.         if ( col < ncols / 2 )
  28.             fprintf( stream, " " );
  29.         for ( i = 0; i < col; i++ )
  30.             fprintf( stream, "%c", isprint( c[ i ] ) ? c[ i ] : '.' );
  31.         fprintf( stream, "\n" );
  32.     }
  33. }
  1. #if defined( STANDALONE )
  2.  
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5.  
  6. int main( void ) {
  7.     unsigned char buf[ 4096 ];
  8.     int n;
  9.  
  10.     while ( (n = read( 0, buf, sizeof ( buf ))) )
  11.         dump( buf, n, stdout );
  12.     exit( 0 );
  13. }
$ gcc -Wall -DDEBUG -DSTANDALONE -o test-dump dump.c
$ test-dump < dump.c
0000 23 69 6e 63 6c 75 64 65  20 22 64 75 6d 70 2e 68 #include "dump.h
0016 22 0a 0a 23 69 6e 63 6c  75 64 65 20 3c 63 74 79 "..#include <cty
0032 70 65 2e 68 3e 0a 0a 76  6f 69 64 20 64 75 6d 70 pe.h>..void dump
0048 28 20 75 6e 73 69 67 6e  65 64 20 63 68 61 72 20 ( unsigned char 
0064 2a 62 75 66 2c 20 73 69  7a 65 5f 74 20 73 69 7a *buf, size_t siz
...

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].