Reading Hard Disk Sectors in C++ on Linux

前端 未结 3 669
天命终不由人
天命终不由人 2021-02-08 13:23

How do you read hard disk sectors in C++ with gcc/linux? Is there a standard library that I can use or must something be downloaded? In Windows I can use CreateFile(...) to acce

3条回答
  •  不思量自难忘°
    2021-02-08 13:48

    The hard disk is just another file (not a "regular file" but a "device file", but still, a file). Open it the normal way...

    int fdes = open("/dev/sda1", O_RDONLY);
    if (fdes < 0)
        err(1, "/dev/sda1");
    ... do more ...
    

    You will get permission errors unless you have the right permissions. Note that "/dev/sda1" is just an example, it is the first partition on disk sda, the exact path will depend on your system. You can list mount points with the mount command, and you can access entire disks (instead of just partitions) using /dev/sda, /dev/sdb, etc.

    You could also open it as a C++ fstream or C FILE, but I do not recommend this. You will have a better time finding example code and getting help on forums if you use open instead.

提交回复
热议问题