c - 读取二进制文件,存入缓冲区,打印缓冲区内容

标签 c malloc buffer binaryfiles fread

在我继续我的程序之前,我有一个大问题需要解决。

我必须打开一个二进制文件,读取它的内容,将内容保存到缓冲区中,使用 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])

希望大家帮帮忙

来自德国的问候:)

最佳答案

建议的更改:

  1. 将缓冲区更改为 char (字节),作为 ftell()将报告字节大小 ( char ) 和 malloc()也使用字节大小。

    无符号整型缓冲区[];/缓冲区/

unsigned char *buffer; /*buffer*/
  1. [编辑] 2021:省略类型转换
    2) 没问题,大小是字节,缓冲区指向字节,但可以显式转换

    缓冲区 = malloc(大小);/在堆上分配空间/

  2. <罢工>
<罢工>

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*/
  1. 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){ 
  1. 更改 "%x""%02x"否则单个数字的十六进制数会混淆输出。例如“1234”是四个字节还是两个字节?

    printf("%x", 缓冲区[i]);

printf("%02x", buffer[i]);
  1. 您在函数结束时的清理可能包括

    关闭(fp); 免费(缓冲区);

关于c - 读取二进制文件,存入缓冲区,打印缓冲区内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16738986/

相关文章:

c - 程序不显示链接列表,但在c中创建链接列表

c - 使用 scanf 和 '%d' 时如何区分 int 和 char

Windows 中的 C++ 高精度时间测量

c - 如何在 memcpy 之前 malloc 结构数组

c - Malloc 被意外中断中断

c++ - malloc 和堆 : extra memory for storing the size and linked list information?

c - 当c中有多个用户时,如何存储有关用户的两条信息

java - 将表示为十六进制字符串的字节数组转换为正确的 int

ios - 缓冲区较小时音频队列播放速度过快

node.js - 如何以express方式发送缓冲区数据?