【问题标题】:Binary reading returning zero二进制读数返回零
【发布时间】:2021-09-10 13:56:37
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 您正在尝试读取positionX*positionX 字节。
  • 我需要读取文件的全部内容,[ positionX ] 是文件中指针的位置,当 [ positionX ] 位于最后一个字节时,循环停止。
  • 请查看fread的文档以及各个参数的含义。 positionX 在您的情况下是文件的大小缓冲区的大小
  • 我在问题中添加了更多细节。我已经阅读了这个文档,看起来我的 fread() 没问题。怎么了 ? docs.microsoft.com/pt-br/cpp/c-runtime-library/reference/…
  • 非常感谢开发人员。

标签: c binary binaryfiles binary-data


【解决方案1】:

您对fread 的调用不正确:

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

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

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

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

【讨论】:

  • buffer 没有写到末尾,因为文件不够大。 buffer 是一个与文件大小完全相同的 VLA。我希望 fread() 返回 1,因为这是可以读取的大小为 sizeof buffer 的元素的数量。 -- 无论如何,要自动获得正确的数字,调用fread(buffer, sizeof buffer[0], sizeof buffer / sizeof buffer[0], file) 会更好。
  • 非常感谢开发人员。
猜你喜欢
  • 1970-01-01
  • 2017-03-14
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
相关资源
最近更新 更多