【发布时间】: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