二进制读数返回零

Binary reading returning zero

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

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
        }
    }
}

谢谢

您对 fread 的调用不正确:

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

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

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

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