c - 一次读取一个二进制文件 1 个字节

标签 c file io binary

我试图一次读取一个 C 1 字节的二进制文件,在互联网上搜索了几个小时后,我仍然无法让它检索除垃圾和/或段错误之外的任何内容。基本上,二进制文件采用列表格式,长度为 256 个项目,每个项目为 1 个字节(0 到 255 之间的无符号整数)。我正在尝试使用 fseek 和 fread 跳转到二进制文件中的“索引”并检索该值。我目前拥有的代码:

unsigned int buffer;

int index = 3; // any index value

size_t indexOffset = 256 * index;
fseek(file, indexOffset, SEEK_SET);
fread(&buffer, 256, 1, file);

printf("%d\n", buffer);

现在这段代码给我随机的垃圾数字和段错误。关于如何让它正常工作的任何提示?

最佳答案

您将 bytesint 混淆了。 byte 的常用术语是 unsigned char。大多数字节为 8 位宽。如果你读的数据是8位的,你就需要按8位读:

#define BUFFER_SIZE 256

unsigned char buffer[BUFFER_SIZE];

/* Read in 256 8-bit numbers into the buffer */
size_t bytes_read = 0;
bytes_read = fread(buffer, sizeof(unsigned char), BUFFER_SIZE, file_ptr);
// Note: sizeof(unsigned char) is for emphasis

将所有数据读入内存的原因是为了保持 I/O 流动。无论请求的数量如何,每个输入请求都会产生开销。一次读取一个字节,或者一次查找一个位置是最坏的情况。

这是读取 1 个字节所需开销的示例:

Tell OS to read from the file.
OS searches to find the file location.
OS tells disk drive to power up.
OS waits for disk drive to get up to speed.
OS tells disk drive to position to the correct track and sector.
-->OS tells disk to read one byte and put into drive buffer.
OS fetches data from drive buffer.
Disk spins down to a stop.
OS returns 1 byte to your program.

在你的程序设计中,上面的步骤会重复256次。根据大家的建议,标有“-->”的行将读取 256 个字节。因此开销只执行一次而不是 256 次以获得相同数量的数据。

关于c - 一次读取一个二进制文件 1 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6093224/

相关文章:

c - 乘以非常大的十六进制数并用 C 打印它们

c - C 中的外部变量及其作用域

Java 相对文件路径

java - 监控 InputStream 的最佳方式是什么?

c - SPOJ 上出现超时错误

c - C 的 XML 解析器

Python 检查文件是否存在,如果存在则更新它,否则创建它

C程序逐行读取文本文件时添加空格

Haskell - 从句柄读取行而不阻塞

c++ - 打印一个 map 的值,它有两个字符串作为键和 vector 作为值