从C中的二进制文件读取值

时间:2019-01-25 16:11:29

标签: c file binaryfiles

这是我的问题:我不知道如何从二进制文件中读取整数。我需要一个解决方案来理解代码背后的问题。

这是我的二进制文件的图像: enter image description here

此格式可存储小尾数形式的32位整数。例如,我们有一个文件,其中包含3个值:1、2和3,采用这种格式,它们将被编码为: 01 00 00 00 02 00 00 00 03 03 00 00 00或01 FF FF FF ...。

我写了一些代码,但我不明白为什么它不起作用。调试不会给我错误。

这是我的代码

#include <stdlib.h>
#include <stdio.h>

int *leggiinteri2(const char *filename, size_t *size)  
{
FILE *f;
int *p = NULL;
f = fopen(filename, "rb");
if (f == NULL) {
    p = NULL;
}
else {
    size_t nInteri = fread(size, sizeof(int), 1, f);
    if (nInteri != 1) {
        if (feof(f)) {
            p = NULL;
        }
        if (ferror(f)) {
            p = NULL;
        }
    }
    else {
        p = malloc(sizeof(int)*((int)size));
        fseek(f, 0, SEEK_SET);
        nInteri = fread(p, sizeof(int), *size, f);
        if (nInteri != *size) {
            if (feof(f)) {
                p = NULL;
            }
            if (ferror(f)) {
                p = NULL;
            }
        }
    }
}
fclose(f);
return p;
}

2 个答案:

答案 0 :(得分:0)

尝试类似的事情:

    fread (buffer, sizeof(char), 8, fid);
    x = (s32)(((buffer[0]<<24) & 0xFF000000) + ((buffer[1]<<16) & 0x00FF0000)
            + ((buffer[2]<< 8) & 0x0000FF00) + ( buffer[3]      & 0x000000FF));

我不确定顺序(小字节序或大字节序)。如果为KO,则反转缓冲区索引3、2、1、0。

答案 1 :(得分:0)

我终于找到了解决方案,虽然花了很多时间,但还是值得的,现在我了解了其背后的逻辑。

这是需要的人的代码:

#include <stdlib.h>
#include <stdio.h>

int *leggiinteri2(const char *filename, size_t *size) 
{
    FILE *f;
    int *p = NULL;
    f = fopen(filename, "rb");
    if (f == NULL) {
        p = NULL;
    }
    else {
        fseek(f, 0, SEEK_END); //It tells me how many values ​​there are in 
                              //the file, both those that I need and those 
                              //that do not 
        long dim = ftell(f); // I assign to dim the value that tells me 
                            //ftell, conditioned by the previous function
        dim = dim / 4; //because I want the integer values (int = 4 bytes)
        *size = dim;
        p = malloc(sizeof(int) * dim);
        fseek(f, 0, 0);
        size_t n = fread(p, sizeof(int), *size, f);
        if (n != *size) {
            if (feof(f)) {
                p = NULL;
            }
            if (ferror(f)) {
                p = NULL;
            }
        }
        if (n == 0) //serves to check for empty or NULL files
            p = NULL;
    }
    fclose(f);
    return p;
}
相关问题