为什么这个程序不能正确读取十六进制文件?
#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);
}
如果我打印一个巨大的十六进制文件,它只会打印 5 到 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 的 block ...
不同的实现
#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;
}
关于从十六进制文件读取的 C 程序给出意外的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11395308/