c - 二进制读数返回零
问题描述
我正在尝试读取二进制文件并在终端中显示其内容,但是这行代码:
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);
推荐阅读
- airflow - 追赶实例之间的气流延迟
- java - Spring Cloud Gateway - 审计日志
- mysql - 在这个例子中如何使用 INNER JOIN
- r - 在R闪亮中隐藏标签面板
- swift - CAShapeLayer 获取当前比例
- python - IndexError:只有整数、切片 (`:`)、省略号 (`...`)、numpy.newaxis (`None`) 和整数或布尔数组是有效的索引增强现实
- r - R 没有要绘制的交易/头寸
- r - 无法安装包“userfriendlyscience”
- ramda.js - ramda 根据原始值更新对象值
- mysql - 更新条件以更改索引行