Before, I post a question here asking for advice on how to read and write data from and into drive, not via file label like "aaa.txt", but just sectors.. I was advised to try read and write.... but new problems'v raised... the hairy parameters
int _read( int handle, void *buffer, unsigned int count );
when i use the function and wanto read sectors from drive...i seems i need to set the count to be x*512. it has to be several times of 512 bytes...
why??? Are there some raw functions allowing me to use directly byte by byte... Thanx... btb, if i wanto do that, I should develope my own I/O driver programs? thanx
Reads and writes to devices must be both sector aligned, and with byte counts that are integer multiples of the sector size.
Don't make assumptions about the sector size, you should query the sector size for any device, and work dynamically with that. Typical sizes are 512 for hard drives, and 2048 for optical drives.
If you want functions that allow you to read byte by byte on devices, without incurring wasteful overhead, try this trick:
If you need to get the sector size on Windows you can call
DeviceIoControl()
withIOCTL_DISK_GET_DRIVE_GEOMETRY
.Stdio will align seeks to
s
and read chunks of sizes
. Additionally you can provide a buffer of your own usingposix_memalign()
, or_aligned_malloc()
, if your underlying stdio implementation doesn't do this.Edit: To clear up some confusion in a comment
You're working with a device with sector size 512, with
FILE *f;
. Youfseek()
to offset 37.f
's position is updated, but no seek is made on the device. Youfread()
500 bytes.lseek()
is called with an offset of 0. 512 bytes are read intof
's buffer. Bytes 37 to 512 are copied to the buffer you provided.lseek()
is called with an offset of 512. 512 bytes are read, and the remaining 463 bytes you're expecting are copied out to the buffer you passed tofread()
. If you were to nowfread()
a single byte, that would simply be copied out of the existing buffer inf
, without hitting the device.