为什么这个程序没有正确读取hex文件?
#include <stdio.h>
#include <stdlib.h>
char *buffer;
unsigned int fileLen;
void ReadFile(char *name);
void ReadFile(char *name)
{
FILE *file;
file = fopen(name, "rb");
if (!file)
{
fprintf(stderr, "Unable to open file %s", name);
return;
}
//Getting file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
//Allocating memory
buffer=(char *)malloc(fileLen+1);
if (!buffer)
{
fprintf(stderr, "Mem error!");
fclose(file);
return;
}
fread(buffer, fileLen, 1, file);
fclose(file);
}
int main()
{
var32 code;
char filename[20];
printf("Enter the file name: ");
scanf("%s", &filename);
ReadFile(filename);
printf("FIle contents: %x\n",buffer);
}
如果我打印一个巨大的hex文件,它只打印5到6位数。
答案 0 :(得分:6)
printf("FIle contents: %x\n",buffer);
“%x”只打印一个十六进制值。它打印缓冲区的内存地址,而不是其内容。
尝试更改:
fread(buffer, fileLen, 1, file);
fclose(file);
之后添加:
...
fclose(file);
size_t i;
for (i = 0; i < fileLen; i++)
printf("%02x ", buffer[i];
这将打印整个二进制内容。但是没有必要读取整个文件来执行此操作,您可以一次输出1 K的块...
不同的实施
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define BUFFER_SIZE 4096
int main(void)
{
uint8_t *buffer; // Explicit 8 bit unsigned, but should equal "unsigned char"
FILE *file;
char filename[512];
// We could also have used buffer[BUFFER_SIZE], but this shows memory alloc
if (NULL == (buffer = malloc(BUFFER_SIZE)))
{
fprintf(stderr, "out of memory\n");
return -1;
}
printf("Enter the file name: ");
// Read a line terminated by LF. Max filename size is MAXPATH, or 512
fgets(filename, 512, stdin);
// Trim filename (Windows: CHECK we don't get \r instead of \n!)
{
// Being inside a { }, crlf won't be visible outside, which is good.
char *crlf;
if (NULL != (crlf = strchr(filename, '\n')))
*crlf = 0x0;
}
if (NULL == (file = fopen(filename, "rb")))
{
fprintf(stderr, "File not found: '%s'\n", filename);
return -1;
}
while(!feof(file) && !ferror(file))
{
size_t i, n;
if (0 == (n = (size_t)fread(buffer, sizeof(uint8_t), BUFFER_SIZE, file)))
if (ferror(file))
fprintf(stderr, "Error reading from %s\n", filename);
// Here, n = 0, so we don't need to break: next i-cycle won't run
for (i = 0; i < n; i++)
{
printf("%02x ", buffer[i]);
if (15 == (i % 16))
printf("\n"); // Every 16th byte, a newline
}
}
fclose(file); // file = NULL; // This ensures file won't be useable after fclose
free(buffer); // buffer = NULL; // This ensures buffer won't be useable after free
printf("\n");
return 0;
}
答案 1 :(得分:4)
printf()
语句将以十六进制格式打印buffer
的地址。您需要printf()
buffer
中的每个字节(,并且必须为null )并确保调用者知道buffer
,以便调用者知道何时停止或返回buffer
中的字节数调用者buffer
中有多少字节(以二进制读取,空终止不安全。)
此外:
buffer
不为空(这是逐字节打印所必需的)fread()
的返回值以确保其成功free()
缓冲区malloc()
不需要(请参阅Do I cast the result of malloc?)scanf()
读取的字节数以避免缓冲区溢出:scanf("%19s", filename);
code
是未使用的本地变量答案 2 :(得分:-1)
如果使用十六进制表示二进制,则无法直接打印,输出将以文件中的第一个零字节结束。
此外,如果找不到该文件,则先说“无法打开文件”,然后继续说“文件内容:...”
正如其他人指出的那样,你正在以错误的方式打印缓冲区。
你没有释放缓冲区。