To read or write directly to blocks on the disk, all you need to do is
open /dev/sda (or whatever the device name is for your disk) and then
use the normal "read", "write" and "lseek" calls to access it just
like a file. Of course, when you call "open" to get the file
descriptor (an integer), be sure you specify O_RDWR. Type "man 2
read", "man 2 lseek", etc for the documentation of each of these
standard system calls. You could probably also use the fopen, fread,
etc calls, but you're probably better off keeping to the unbuffered
(at the C library level) calls.
Beware of calling lseek beyond the end of the disk and then accessing
it, particularly if the disk is a USB-based flash media card using the
SCSI emulation layer (sometimes linux 2.4.18 will mis-detect the disk
geometry and thus the total size after a hot-swap).
You could write lots of code to format the disk by writing directly
into the sectors, or you could just call one of the existing format
commands (mke2fs, mkdosfs, etc) using the "system" call. Don't forget
to check the return value to see if the command was successful. Type
"man 3 system" for details if you've not used the system call. It's
really very simple.
If you write to the partition table, there is some ioctl you must call
(you'll have to look it up, since this is a free comment and not a
paid answer). If you're intending to only access within an existing
partition, you can open /dev/sda1, /dev/sda2, etc and the kernel will
make offset 0 the beginning of that partition and prevent writes from
spilling onto the other partitions.
Also, everything I've said here works equally well for IDE disks
(/dev/hda, /dev/hdb, etc). |