首页 > 解决方案 > 二进制读数返回零

问题描述

我正在尝试读取二进制文件并在终端中显示其内容,但是这行代码:

size_t readed = fread(buffer, sizeof(buffer), positionX, file);

它返回零,所以我的循环停止了,解决这个问题的建议是什么?

buffer = Storage
sizeof(buffer) = Size File
positionX = 7918080 <-- Dynamic Pointer
file = File to read

终端输出:

https://i.stack.imgur.com/i9pls.png

我的完整代码:

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

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        printf("Usage: Please insert the file to read\n");
        return 1;
    }
    else
    {
        FILE *file;

        file = fopen(argv[1], "rb");

        //Cannot open file --> check pointer file after fopen
        if (file == NULL)
        {
            printf("Cannot open file \n");
            exit(0);
        }

        long positionX = ftell(file);

        printf("Pointer at the beginning %ld\n", positionX);

        fseek(file, 0, SEEK_END);

        positionX = ftell(file);

        rewind (file); // Sets the position indicator associated with stream to the beginning of the file

        unsigned char buffer[positionX]; // o buffer deveria ser criado aqui depois de pegar a posição final

        printf("Pointer at the End: %ld\n", positionX);

        // Read the content --> it's always good to check the read value
        // the third parameter was 1, it should be "position"
        size_t readed = fread(buffer, sizeof(buffer), positionX, file);

        printf("the size is %zu\n", readed);  // decimal size_t ("u" for unsigned)
        printf("the size is %zx\n", readed);  // hex size_t

        for(size_t i = 0; i < readed; i++) // usar readed como limite
        {
            printf("%x ", buffer[i]); // prints a series of bytes
        }
    }
}

谢谢

标签: cbinarybinaryfilesbinary-data

解决方案


您的调用fread不正确:

size_t readed = fread(buffer, sizeof(buffer), positionX, file);

第二个参数是要读取的每个元素的大小,第三个是元素的数量。这意味着您正在尝试读取最多sizeof(buffer) * positionX字节,但buffer不是那么大。结果,您写入缓冲区的末尾会触发未定义的行为。

由于您正在阅读positionX单个字符,因此您需要 1 作为成员大小:

size_t readed = fread(buffer, 1, positionX, file);

推荐阅读