Question: The program is done in C. This program opens a file containing binary or text and reads every byte in the file and writes both
The program is done in C. This program opens a file containing binary or text and reads every byte in the file and writes both the ASCII hex value for that byte as well as its printable (human-readable) character (characters, digits, symbols) to standard output. The issue I am having is when the file has multiple lines being read. The first line is read and done properly but the other lines do not work correctly. For instance, the text file will contain this:
.......1.unsigne
...unsigned char
------------------------
and results in: 0000000: 2e2e 2e2e 2e2e 2e31 2e75 6e73 6967 6e65 .......1.unsigne
0000010: 0a00 0000 0000 0000 0000 0000 0000 0000 ................
but should result in: 0000000: 2e2e 2e2e 2e2e 2e31 2e75 6e73 6967 6e65 .......1.unsigne
0000010: 2e2e 2e75 6e73 6967 6e65 6420 6368 6172 ...unsigned char
Any ideas on how to fix this?
--------------------------------------------------------------------
CODE
--------------------------------------------------------------------
#include
#define SIZE 1000
void hexDump (char *desc, void *addr, int len) { int i; unsigned char buffline[17]; unsigned char *pc = (unsigned char*)addr; if(desc != NULL){ printf("%s: ", desc); } for (i = 0; i < len; i++){ if ((i % 16) == 0){ if (i != 0) printf(" %s ", buffline); if(pc[i] == 0x00) exit (0); printf(" %07x: ", i); //prints address } printf ("%02x", pc[i]); if ((i % 2) == 1) printf(" "); if ((pc[i] < 0x20) || (pc[i] > 0x7e)){ //non-printable chars buffline[i % 16] = '.'; } else{ buffline[i % 16] = pc[i]; } buffline[(i % 16) + 1] = '\0'; //clear array } while ((i % 16) != 0) { //'.' fill last line printf (" "); i++; } printf (" %s ", buffline); }
int main (int argc, char *argv[]) { FILE *fp; char buff[SIZE]; fp = fopen(argv[1], "r"); memset(buff, '\0', sizeof(buff)); fgets(buff, SIZE, fp); hexDump("buff", &buff, sizeof(buff)); fclose(fp); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
