读取二进制文件,保存在缓冲区中,打印出缓冲区的内容

时间:2013-05-24 15:52:51

标签: 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 个答案:

答案 0 :(得分:7)

推荐的更改:

1)将缓冲区更改为char(字节),因为ftell()将以字节为单位报告大小(char),malloc()也使用字节大小

unsigned int buffer []; /*buffer*/

unsigned char *buffer; /*buffer*/

2)这没关系,size是字节,缓冲区指向字节,但可以显式转换

buffer = malloc(size);  /*allocate space on heap*/

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*/

3)将第二个参数从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){ 

4)将"%x"更改为"%02x"否则单个数字的十六进制数字会混淆输出。 E. g。是“1234”四个字节还是两个?

printf("%x", buffer[i]);

printf("%02x", buffer[i]);

5)你在功能结束时的清理可能包括

fclose(fp);
free(buffer);