你的令人困惑的字节与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
将所有数据读入存储器的原因是为了保持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次以获得相同数量的数据 .