Question: Write a C program which will display the contents of a file in base-16 (hexadecimal) and in ASCII. Complete the following tasks: Obtain the name
Write a C program which will display the contents of a file in base-16 (hexadecimal) and in ASCII.
Complete the following tasks:
- Obtain the name of the input file from the command line. If the command-line is ./hexdump xxx.bin then argv[1] will contain xxx.bin.
- Open the file for binary input
- Print the entire file, 16-bytes per line. Each line should begin with an 8-digit hexadecimal offset into the file. This is the count of the bytes that you have already printed, and therefore begins with 00000000. Each of the 16 bytes should be printed as a 2-digit hexadecimal value separated by spaces. Print leading zeros if necessary to ensure 2 digits. After all 16 bytes are printed, display any values which are printable as ASCII characters, and display any non-printable values as .. Therefore there will be 16 symbols at the end of the line.
Some useful hints:
- An integer can be printed in hexadecimal by using the format string %x. If you want to fix the width of the printed value, put the width before the x %8x. If you want leading zeros to ensure all values have the same width, put a 0 before this: %08x. This works for any number of digits.
- To determine if a character is printable, include the header
and use the isprint(c) macro. This checks if the character in the variable c is printable, and returns true or false. - To print a value as a character, use the %c format string.
- To print a linefeed, add to your format string. If your printf does not have this linefeed, then the next printf will append to the current line. This is how you can print several values on a line in a loop.
- File I/O can be done using fopen and fread. Look at the man pages for these, man 3 fopen, man 3 fread
- You can check for end-of-file with feof().
Requirements:
- Your program should be named hexdump.c without the quotes.
Sample Output (user input is in bold)
hexdump -C yyy.bin
00000000 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 |.ELF............| 00000010 03 00 03 00 01 00 00 00 f7 32 00 00 34 00 00 00 |.........2..4...| 00000020 94 51 02 00 00 00 00 00
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
