我正在尝试编写一个简单的程序来从文件生成十六进制输出。这是我的two.c
文件:
#include <stdio.h>
int
main(void) {
printf("%s\n", "Hello");
return 0;
}
以这种方式编译的:
gcc -std=c99 -Wall -Wextra -pedantic-errors two.c -o two
所以我有two
可执行文件。
现在,我编写了一个程序来读取该文件并显示它的二进制(十六进制)输出。这是我的程序:
#include <stdio.h>
int
fileSize(FILE *ptr) {
int size = 0;
fseek(ptr, 0, SEEK_END);
size = ftell(ptr);
fseek(ptr, 0, SEEK_SET);
return size;
}
int
main(void) {
FILE *fp;
fp = fopen("two", "rb");
int sz = fileSize(fp);
char buff[ sz ];
if (!fp)
printf("%s\n", "Not great at all");
else
while (!feof(fp)) {
fgets(buff, sz, fp);
for (int i = 0; i < sz; i++) {
printf("%02x%02x ", (buff[i] & 0xFF), (buff[i+1] & 0xFF));
if (!(i % 8))
printf("\n");
}
printf("\n");
}
fclose(fp);
}
这是它的巨大输出http://pastebin.com/RVLy6H9B
问题是,当我使用 linux 命令时,xxd two > two.hex
我得到了完全不同的输出(这与格式化无关),并且只有大约 500 行字节,而不是像我的输出那样大约 8k。
xxd 输出: http: //pastebin.com/Gw9wg93g
问题出在哪里?阅读功能有问题fgets(buff, sz, fp);
吗?