78 lines
1.3 KiB
C++
78 lines
1.3 KiB
C++
|
#include "FileIO.h"
|
||
|
|
||
|
#include <stdint.h> /* uint8_t */
|
||
|
#include <stdio.h>
|
||
|
#include <math.h>
|
||
|
|
||
|
#include <errno.h> /* errno */
|
||
|
#include <string.h> /* strerror */
|
||
|
|
||
|
static int
|
||
|
IsProbablyAscii (const void *buf, const size_t len)
|
||
|
{
|
||
|
const uint8_t *bufPtr;
|
||
|
const uint8_t *bufPtrEnd;
|
||
|
size_t nAsciiCount;
|
||
|
nAsciiCount = 0;
|
||
|
bufPtr = (const uint8_t *) buf;
|
||
|
bufPtrEnd = bufPtr + len;
|
||
|
while (bufPtr < bufPtrEnd && (NULL != bufPtr) && (*bufPtr != '\0'))
|
||
|
{
|
||
|
nAsciiCount += (*bufPtr >= ' ') && (*bufPtr <= '~');
|
||
|
bufPtr++;
|
||
|
}
|
||
|
return (int) round ((double) nAsciiCount / (double) len);
|
||
|
}
|
||
|
|
||
|
|
||
|
static void
|
||
|
HexDump (const void *buf, const size_t len)
|
||
|
{
|
||
|
const uint8_t *bufPtr;
|
||
|
const uint8_t *bufPtrEnd;
|
||
|
const size_t width = 16;
|
||
|
size_t nout;
|
||
|
nout = 0;
|
||
|
bufPtr = (const uint8_t *) buf;
|
||
|
bufPtrEnd = bufPtr + len;
|
||
|
while (bufPtr < bufPtrEnd && (NULL != bufPtr))
|
||
|
{
|
||
|
if (nout == width)
|
||
|
{
|
||
|
printf ("\n");
|
||
|
nout = 0;
|
||
|
}
|
||
|
printf ("%02x ", *bufPtr);
|
||
|
bufPtr++;
|
||
|
nout++;
|
||
|
}
|
||
|
puts ("");
|
||
|
}
|
||
|
|
||
|
|
||
|
int
|
||
|
main (int argc, char **argv)
|
||
|
{
|
||
|
int rc;
|
||
|
rc = 1;
|
||
|
try
|
||
|
{
|
||
|
while (argc-- > 1)
|
||
|
{
|
||
|
FileIO f (argv[argc], "r");
|
||
|
std::string buf = f.ReadToString ();
|
||
|
if (IsProbablyAscii (buf.c_str (), buf.size ()))
|
||
|
printf ("%s", buf.c_str ());
|
||
|
else
|
||
|
HexDump (buf.c_str (), buf.size ());
|
||
|
rc = 0;
|
||
|
}
|
||
|
}
|
||
|
catch (int err)
|
||
|
{
|
||
|
puts (strerror (errno));
|
||
|
}
|
||
|
|
||
|
return rc;
|
||
|
}
|