1 using System;
2 using System.Collections;
3 using System.IO;
4
5 void PrintHelp()
6 {
7 Console.WriteLine("Usage: hexdump [options] { <filename> }");
8 Console.WriteLine("options:");
9 Console.WriteLine("--help | -h");
10 Console.WriteLine(" print this help");
11 }
12
13 const uint bytesInLine = 16u;
14
15 string HexDumpLine(uint addr, byte* bytes, uint numBytes)
16 {
17 #assert(numBytes > 0 && numBytes <= bytesInLine);
18 string line(ToHexString(addr));
19 line.Append(": ");
20 for (uint i = 0u; i < bytesInLine; ++i;)
21 {
22 if (i == bytesInLine / 2)
23 {
24 line.Append("- ");
25 }
26 if (i < numBytes)
27 {
28 line.Append(ToHexString(bytes[i]));
29 }
30 else
31 {
32 line.Append(" ");
33 }
34 line.Append(' ');
35 }
36 line.Append('|');
37 for (uint i = 0u; i < bytesInLine; ++i;)
38 {
39 char c = ' ';
40 if (i < numBytes)
41 {
42 char b = cast<char>(bytes[i]);
43 if (IsPrintable(b))
44 {
45 c = b;
46 }
47 }
48 line.Append(c);
49 }
50 line.Append('|');
51 return line;
52 }
53
54 void HexDump(const string& fileName)
55 {
56 Console.WriteLine(fileName + ":");
57 long fileSize = File.Size(fileName);
58 BinaryReader reader = File.OpenBinary(fileName);
59 byte[bytesInLine] bytes;
60 uint addr = 0u;
61 long numRows = fileSize / bytesInLine;
62 for (ulong i = 0u; i < numRows; ++i;)
63 {
64 for (uint j = 0u; j < bytesInLine; ++j;)
65 {
66 bytes[j] = reader.ReadByte();
67 }
68 Console.WriteLine(HexDumpLine(addr, &bytes[0], bytesInLine));
69 addr = addr + bytesInLine;
70 }
71 uint rest = cast<uint>(fileSize % bytesInLine);
72 for (uint j = 0u; j < rest; ++j;)
73 {
74 bytes[j] = reader.ReadByte();
75 }
76 Console.WriteLine(HexDumpLine(addr, &bytes[0], rest));
77 addr = addr + rest;
78 uint size = addr;
79 string sizeLine = ToHexString(size);
80 sizeLine.Append(';');
81 Console.WriteLine(sizeLine);
82 }
83
84 int main(int argc, const char** argv)
85 {
86 try
87 {
88 List<string> fileNames;
89 for (int i = 1; i < argc; ++i;)
90 {
91 string arg = argv[i];
92 if (arg.StartsWith("-"))
93 {
94 if (arg == "--help" || arg == "-h")
95 {
96 PrintHelp();
97 return 0;
98 }
99 else
100 {
101 throw Exception("unknown arguent '" + arg + "'");
102 }
103 }
104 else
105 {
106 fileNames.Add(GetFullPath(arg));
107 }
108 }
109 if (fileNames.IsEmpty())
110 {
111 throw Exception("no files given");
112 }
113 else
114 {
115 for (const string& fileName : fileNames)
116 {
117 HexDump(fileName);
118 }
119 }
120 }
121 catch (const Exception& ex)
122 {
123 Console.Error() << ex.ToString() << endl();
124 return 1;
125 }
126 return 0;
127 }