-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHexDump.cpp
118 lines (105 loc) · 2.99 KB
/
HexDump.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <tchar.h>
#include <ctype.h>
#include <stdlib.h>
#include "arg.inl"
typedef unsigned char BYTE;
void setcolor(int* curcolor, int c)
{
if (*curcolor != c)
{
_tprintf(_T("\x1b[%dm"), c);
*curcolor = c;
}
}
int _tmain(int argc, const TCHAR* argv[])
{
arginit(argc, argv);
bool color = _isatty(_fileno(stdout));
if (argswitch(_T("/color")))
color = true;
if (argswitch(_T("/nocolor")))
color = false;
bool squeeze = !argswitchdesc(_T("/nosqueeze"), _T("Do not skip over like lines"));
const TCHAR* filename = argnumdesc(1, nullptr, _T("filename"), nullptr);
if (!argcleanup())
return EXIT_FAILURE;
if (filename == nullptr && !_isatty(_fileno(stdin)))
filename = _T("-");
if (argusage(filename == nullptr))
return EXIT_SUCCESS;
FILE* input = nullptr;
if (_tcscmp(filename, _T("-")) == 0)
{
input = stdin;
int result = _setmode(_fileno(stdin), _O_BINARY);
if (result == -1)
{
_ftprintf(stderr, _T("Error setting input mode: %d\n"), errno);
return EXIT_FAILURE;
}
}
else
{
errno_t e = _tfopen_s(&input, filename, _T("rb"));
if (e != 0)
{
_ftprintf(stderr, _T("Error opening file: %d\n"), e);
return EXIT_FAILURE;
}
}
const size_t size = 16;
int curcolor = 0;
BYTE* data = new BYTE[size];
BYTE* prev = new BYTE[size];
size_t prevcount = 0;
bool same = false;
size_t offset = 0;
while (true)
{
const size_t count = fread_s(data, size * sizeof(BYTE), 1, size, input);
if (count == 0)
break;
if (squeeze && count == prevcount && memcmp(prev, data, count * sizeof(BYTE)) == 0)
{
if (!same)
_tprintf(_T(" ***\n"));
same = true;
}
else
{
same = false;
if (color) setcolor(&curcolor, 33);
_tprintf(_T("%08Xh:"), (unsigned int) offset);
for (size_t i = 0; i < count; ++i)
{
bool isp = isprint(data[i]) != 0;
if (color) setcolor(&curcolor, isp ? 34 : 0);
_tprintf(_T(" %02X"), data[i]);
}
for (size_t i = count; i < size; ++i)
{
_tprintf(_T(" "));
}
_tprintf(_T(" "));
for (size_t i = 0; i < count; ++i)
{
bool isp = isprint(data[i]) != 0;
if (color) setcolor(&curcolor, isp ? 34 : 0);
_tprintf(_T("%c"), isp ? data[i] : '.');
}
_tprintf(_T("\n"));
memcpy(prev, data, count * sizeof(BYTE));
prevcount = count;
}
offset += count;
}
if (color) setcolor(&curcolor, 0);
delete[] data;
delete[] prev;
if (input != stdin)
fclose(input);
return EXIT_SUCCESS;
}