16 #define CEIL(x, y) (((x) + (y) - 1) / (y))
17 #define MIN(x, y) (((x) < (y)) ? (x) : (y))
18 #define MAX(x, y) (((x) > (y)) ? (x) : (y))
20 //#define BUFFERSIZE 4096
21 #define BUFFERSIZE 256
26 char *progname
= NULL
;
32 FILE *fd
= ret
? stderr
: stdout
;
33 fprintf (fd
, "usage: %s [-i file] [-h] [-n nbcols] [-o file] [-v]\n", progname
);
34 fprintf (fd
, " -i : input file\n");
35 fprintf (fd
, " -h : help message\n");
36 fprintf (fd
, " -n : number of columns\n");
37 fprintf (fd
, " -o : output file\n");
38 fprintf (fd
, " -v : verbose level (%d)\n", verbose
);
43 /* get number of digits */
45 int getnbdigits (long int l
) {
56 void printline (char *buffer
, int nbcols
, int nb
, int addr
, int nbdigits
) {
59 printf ("0x%0*x:", nbdigits
, addr
);
60 for (i
= 0; i
< nb
; i
++) {
61 printf (" %02x", buffer
[i
]);
63 for (i
= nb
; i
< nbcols
; i
++) {
67 for (i
= 0; i
< nb
; i
++) {
69 printf ("%c", (c
> 31) && (c
< 127) ? c
: '.');
76 int hexdump (FILE *fin
, int nbcols
) {
77 char buffer
[BUFFERSIZE
] = {0};
85 fseek (fin
, 0 , SEEK_END
);
86 long int filesize
= ftell (fin
);
87 fseek (fin
, 0 , SEEK_SET
);
88 nbdigits
= getnbdigits (filesize
);
96 nb
+= fread (pt
, 1, BUFFERSIZE
- (pt
- buffer
), fin
);
100 while ((nb
- (int)(pt
- buffer
)) / nbcols
> 0) {
101 printline (pt
, nbcols
, nbcols
, addr
, nbdigits
);
106 /* copy end buffer */
108 for (i
= 0; i
< nb
; i
++) {
116 printline (buffer
, nbcols
, nb
, addr
, nbdigits
);
124 int main (int argc
, char *argv
[])
131 char *pt
= progname
= argv
[0];
133 if ((*pt
== '/') || (*pt
== '\\')) {
140 while ((c
= getopt(argc
, argv
, "i:hn:o:v:")) != EOF
) {
146 nbcols
= atoi (optarg
);
152 verbose
= atoi (optarg
);
159 if (argc
- optind
!= 0) {
160 fprintf (stderr
, "%s: invalid option -- %s\n", progname
, argv
[optind
]);
167 fin
= fopen (input
, "rb");
169 VERBOSE (ERROR
, fprintf (stderr
, "error: can't open file '%s'\n", input
));
178 fout
= fopen (input
, "wb");
180 VERBOSE (ERROR
, fprintf (stderr
, "error: can't open file '%s'\n", output
));
187 hexdump (fin
, nbcols
);
196 // test: hexdump.exe -h
197 // test: hexdump.exe -h | awk '/usage:/ { rc=1 } END { exit (1-rc) }'
198 // test: hexdump.exe -_ 2> /dev/null | awk 'END { if (NR == 0) { exit(0) } else exit (1) }'
199 // test: hexdump.exe -_ 2>&1 | awk '/usage:/ { rc=1 } END { exit (1-rc) }'
200 // test: hexdump.exe -i hexdump.c | grep -q '0x[0-9a-f]*: '
201 // test: hexdump.exe -i hexdump.c -n 3|head -2|tail -1| grep '0x0003: 64 65 70 dep'
203 /* vim: set ts=4 sw=4 et: */