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

Rog*_*erB 18 c io binary file

我试图一次读取C 1字节的二进制文件,并在搜索互联网几个小时后仍然无法检索除垃圾和/或seg故障之外的任何内容.基本上,二进制文件的格式为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);
Run Code Online (Sandbox Code Playgroud)

现在这段代码给了我随机的垃圾数字和段错误.有关如何使其正常工作的任何提示?

MBy*_*ByD 16

在您的代码中,您尝试将256个字节读取到一个int的地址.如果要一次读取一个字节,请调用fread(&buffer, 1, 1, file);(参见fread).

但更简单的解决方案是声明一个字节数组,一起读取并在此之后处理它.


Tho*_*ews 15

你的令人困惑的字节int.字节的常用术语是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
Run Code Online (Sandbox Code Playgroud)

将所有数据读入存储器的原因是为了保持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.
Run Code Online (Sandbox Code Playgroud)

在您的程序设计中,上述步骤将重复256次.根据每个人的建议,标有" - >"的行将读取256个字节.因此,开销仅执行一次而不是256次以获得相同数量的数据.

  • 好戏剧化. (3认同)