Direct access to hard disk with no FS from C program on Linux

后端 未结 3 2181
天涯浪人
天涯浪人 2020-11-30 06:18

I want to access the whole hard disk directly from a C program. There\'s no FS on it and never\'s gonna be one.

I just want to open /dev/sda (for example) and do I

3条回答
  •  爱一瞬间的悲伤
    2020-11-30 07:23

    Yes, as others have noted, you can simply open the block device.

    However, it's a really good idea to do IO (writes anyway) on block boundaries and whole blocks. You can use something like pread() and pwrite() to do these IO, or mmap some or all of the device.

    There are a bunch of ioctls which can be used, see "man sd" for some more info. They don't seem to all be documented in the same place.

    In linux/fs.h BLKROSET and a bunch of other ioctls are defined, you have to look around to find out how to use them. You can do useful things like find out how big the device is, and what the block size is.

    The source code of the util-linux-ng package is your friend, it contains examples.

提交回复
热议问题