在我继续我的程序之前,我有一个大问题需要解决。
我必须打开一个二进制文件,读取它的内容,将内容保存到缓冲区中,使用 malloc 在堆上分配空间,关闭文件,最后 printf(.bin 文件的内容)。我走到这一步(关闭文件尚未实现):
void executeFile(char *path){
FILE *fp; /*filepointer*/
size_t size; /*filesize*/
unsigned int buffer []; /*buffer*/
fp = fopen(path,"rb"); /*open file*/
fseek(fp, 0, SEEK_END);
size = ftell(fp); /*calc the size needed*/
fseek(fp, 0, SEEK_SET);
buffer = malloc(size); /*allocalte space on heap*/
if (fp == NULL){ /*ERROR detection if file == empty*/
printf("Error: There was an Error reading the file %s \n", path);
exit(1);
}
else if (fread(&buffer, sizeof(unsigned int), size, fp) != size){ /* if count of read bytes != calculated size of .bin file -> ERROR*/
printf("Error: There was an Error reading the file %s - %d\n", path, r);
exit(1);
}else{int i;
for(i=0; i<size;i++){
printf("%x", buffer[i]);
}
}
}
我想我弄乱了缓冲区,我不确定我是否正确读取了 .bin 文件,因为我无法使用 printf("%x", buffer[i])
希望大家帮帮忙
来自德国的问候:)
最佳答案
建议的更改:
将缓冲区更改为
char
(字节),作为ftell()
将报告字节大小 (char
) 和malloc()
也使用字节大小。无符号整型缓冲区[];/缓冲区/
到
unsigned char *buffer; /*buffer*/
[编辑] 2021:省略类型转换
2) 没问题,大小是字节,缓冲区指向字节,但可以显式转换缓冲区 = malloc(大小);/在堆上分配空间/
罢工> <罢工>
罢工>
到
buffer = (unsigned char *) malloc(size); /*allocate space on heap*/
/* or for those who recommend no casting on malloc() */
buffer = malloc(size); /*allocate space on heap*/
罢工>
从
sizeof(unsigned int)
更改第二个参数至sizeof *buffer
, 即 1。else if (fread(buffer, sizeof(unsigned int), size, fp) != size){
到
else if (fread(buffer, sizeof *buffer, size, fp) != size){
更改
"%x"
至"%02x"
否则单个数字的十六进制数会混淆输出。例如“1234”是四个字节还是两个字节?printf("%x", 缓冲区[i]);
到
printf("%02x", buffer[i]);
您在函数结束时的清理可能包括
关闭(fp); 免费(缓冲区);
关于c - 读取二进制文件,存入缓冲区,打印缓冲区内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16738986/