Created
February 9, 2025 07:35
-
-
Save sam-caldwell/dc10ad4073fa702ae54cb533652e3894 to your computer and use it in GitHub Desktop.
simple hexdump
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <iomanip> | |
#include <vector> | |
using std::cerr; | |
using std::cout; | |
using std::endl; | |
using std::hex; | |
using std::ifstream; | |
using std::ios; | |
using std::setfill; | |
using std::setw; | |
using std::vector; | |
/** | |
* @brief Print the hex dump of a file. | |
* | |
* Read the specified file in binary mode and prints its contents in a hex dump format. | |
* Show the linear address (in hex) on the left and up to 20 bytes of data on the right. | |
* | |
* @param filename The name of the file to dump. | |
* @return int Returns 0 on success, non-zero on failure. | |
*/ | |
int hexDump(const char* filename) { | |
ifstream file(filename, ios::binary); | |
if (!file) { | |
cerr << "Error: Could not open file " << filename << endl; | |
return 1; | |
} | |
const int bytesPerLine = 20; | |
unsigned long address = 0; | |
vector<unsigned char> buffer(bytesPerLine); | |
while (file) { | |
file.read(reinterpret_cast<char*>(buffer.data()), bytesPerLine); | |
std::streamsize bytesRead = file.gcount(); | |
if (bytesRead <= 0) break; | |
// Print linear address. | |
cout << setfill('0') << setw(8) << hex << address << ": "; | |
// Print each byte in hex with a space. | |
for (std::streamsize i = 0; i < bytesRead; i++) { | |
cout << setfill('0') << setw(2) << hex << static_cast<int>(buffer[i]); | |
if (i != bytesRead - 1) | |
cout << " "; | |
} | |
cout << endl; | |
address += bytesRead; | |
} | |
return 0; | |
} | |
/** | |
* @brief Main function. | |
* | |
* Parse command-line arguments, call the hexDump function. | |
* | |
* @param argc Number of command-line arguments. | |
* @param argv Array of command-line argument strings. | |
* @return int Returns 0 on success, non-zero on failure. | |
*/ | |
int main(int argc, char* argv[]) { | |
if (argc < 2) { | |
cerr << "Usage: " << argv[0] << " <filename> is required" << endl; | |
return 1; | |
} | |
return hexDump(argv[1]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment