你如何在C中正确地read/write一个块设备?

How do you properly read/write a block device in C?

我知道您可以对块设备(/dev/sda 等)使用常规 I/O 函数,但是您可以只读取一些大小为 n 的数据吗,还是必须能被 512 整除?是否有任何无意中听到较小尺寸的阅读?有些设备的块大于 512 字节,如果较小的块有开销,我怎么知道最佳块大小?

根据 Wikipedia 以及 Unix 和类 Unix 系统(因此 Linux):

Block special files or block devices provide buffered access to hardware devices, and provide some abstraction from their specifics. Unlike character devices, block devices will always allow the programmer to read or write a block of any size (including single characters/bytes) and any alignment. The downside is that because block devices are buffered, the programmer does not know how long it will take before written data is passed from the kernel's buffers to the actual device, or indeed in what order two separate writes will arrive at the physical device...

这意味着您可以使用任何大小进行读取。由于 in driver 缓冲,物理读取将始终读取物理扇区。