我正在尝试编写一个 C 可执行文件,它将产生与默认xxd
命令相同的输出。例如,假设我有一个名为的相当小的文本文件test.txt
和一个名为的可执行文件myxxd
因此,我首先使用以下方法进行比较基准:
$ touch correct-xxdoutput.txt test-output.txt
$ xxd test.txt > correct-xxdoutput.txt
然后使用我的可执行文件进行相同的操作,但使用不同的输出文件:
$ ./myxxd test.txt > test-output.txt
$ diff correct-xxdoutput.txt test-output.txt
$
我已经非常接近了一些猜测,但是我的格式总是以某种方式出错,而且我并不真正了解具体是如何xxd
生成 hexDumps 的。感觉就像我在这里采取了完全错误的方法,但也许这项任务超出了我目前的 C 知识水平的潜力。
我的代码(另见:https ://pastebin.com/Vjkm8Wb4 ):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 256
//Prototypes
void hexDump(void*, int);
int main(int argc, char *argv[])
{
//Create and open filestream
FILE *myfile;
myfile =fopen(argv[1],"rb");
for ( ; ; )
{
unsigned char buffer[SIZE];
size_t n = fread(buffer, 1, SIZE, myfile);
if (n > 0)
hexDump(buffer, n);
if (n < SIZE)
break;
}
fclose(myfile);
return 0;
}
void hexDump (void *addr, int len)
{
int i;
unsigned char bufferLine[17];
unsigned char *pc = (unsigned char*)addr;
for (i = 0; i < len; i++)
{
if ((i % 16) == 0)
{
if (i != 0)
printf (" %s\n", bufferLine);
if (pc[i] == 0x00) exit(0);
printf ("%08x: ", i);
}
// Prints Hexcdoes that represent each chars.
printf ("%02x", pc[i]);
if ((i % 2) == 1)
printf (" ");
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
{
bufferLine[i % 16] = '.';
}
else
{
bufferLine[i % 16] = pc[i];
}
bufferLine[(i % 16) + 1] = '\0'; //Clears the next array buffLine
}
while ((i % 16) != 0)
{
printf (" ");
i++;
}
printf (" %s\n", bufferLine);
}