【发布时间】:2014-10-03 11:29:55
【问题描述】:
我正在尝试编写一个简单的程序来从文件生成十六进制输出。这是我的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);有问题吗?
【问题讨论】:
-
这里
fp = fopen("two", "rb");你正在打开哪个文件two.c或two.o? -
我正在打开
two文件 - gcc 编译的输出。
标签: c filesize fgets hexdump xxd