clinuxblock-device

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


I know you can use regular I/O functions for block devices (/dev/sda etc), but can you just read some data of size n, or does it have to be divisible by 512? Is there any overheard to reading in smaller sizes? Some devices have blocks bigger than 512 bytes, if there is overhead for smaller sizes, how can I know the optimal block size?


Solution

  • According to Wikipedia and for Unix and Unix-like systems (hence 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...

    That means that you can use use any size for a read. Because of the in driver buffering, the physical reads will always read physical sectors.