#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
#include <readline/readline.h>
#include <readline/history.h>
void HexdumpFile(unsigned char *buffer, int len);
unsigned char *ReadFile(char *fname, int *retlen);
int main(int argc, char **argv) {
char *nextfilename;
while (1) {
unsigned char *fcontent;
int retlen;
nextfilename = readline("Enter a filename: ");
if (nextfilename == NULL)
break;
fcontent = ReadFile(nextfilename, &retlen);
if (fcontent == NULL) {
fprintf(stderr, "Couldn't read file '%s': ", nextfilename);
perror(NULL);
exit(EXIT_FAILURE);
}
HexdumpFile(fcontent, retlen);
free(fcontent);
free(nextfilename);
}
return EXIT_SUCCESS;
}
#define READSIZE 1000
unsigned char *ReadFile(char *fname, int *retlen) {
unsigned char *buf = NULL;
FILE *f;
int readlen, count = 0;
f = fopen(fname, "rb");
if (f == NULL)
return NULL;
buf = (unsigned char *) realloc(buf, READSIZE);
assert(buf != NULL);
while ((readlen = fread(buf+count, 1, READSIZE, f)) > 0) {
count += readlen;
buf = (unsigned char *) realloc(buf, count + READSIZE);
assert(buf != NULL);
}
if (ferror(f)) {
free(buf);
buf = NULL;
count = 0;
}
fclose(f);
*retlen = count;
return buf;
}
void HexdumpFile(unsigned char *buffer, int buflen) {
int count = 0;
int bytesleft = buflen;
while (bytesleft > 0) {
int nextcount = (bytesleft >= 16) ? 16 : bytesleft;
int i;
fprintf(stdout, "%07x", count);
for (i = 0; i < nextcount; i++) {
fprintf(stdout, " %02x", buffer[count + i]);
}
fprintf(stdout, "\n");
count += nextcount;
bytesleft -= nextcount;
}
}