Question: Program is done in C. Currently the program opens a file and reads every byte in the file and write both the ASCII hex value

Program is done in C. Currently the program opens a file and reads every byte in the file and write both the ASCII hex value for that byte as well as its printable character to standard output with non-printable characters printing a "." Now, I want have an option where the program prints in binary instead of hex using the -b at the command line. For instance, ~hexdump -b input.txt(or any name of text file) will result in the binary option and ~hexdump input.txt results in the hex option. Any ideas how to implement the binary portion of this?

-----------------------------------------

#include #include #include

#define SIZE 1000

void hexDump(void * addr, int len) { // no need to pass desc message int i; unsigned char buffline[17]; unsigned char * pc = (unsigned char * ) addr; /*if (desc != NULL) { printf("%s: ", desc); //removing this message you should add this is main }*/ for (i = 0; i < len; i++) { if ((i % 16) == 0) { if (i != 0) printf(" %s ", buffline); if (pc[i] == 0x00) { return; //exit will end the program and you cant modify next line } 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]; int count=1; fp = fopen(argv[1], "r"); memset(buff, '\0', sizeof(buff)); while(fgets(buff, SIZE, fp)){ // added for reading multiple lines in a file hexDump(& buff, sizeof(buff)); } fclose(fp);; return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!