Reading Hard Disk Sectors in C++ on Linux

前端 未结 3 662
天命终不由人
天命终不由人 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:35

    As others have correctly pointed out, disk access on Linux (and other Unix-like operating systems) is via a device special file. On my Ubuntu laptop, my hard drive is named "/dev/sda".

    Since you specifically ask how to do it in C++ (not merely how to do it in Linux), here is how to read one sector using std::ifstream.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
      // Which disk?
      char diskName[] = "/dev/sda";
      std::string diskError = std::string() + diskName + ": ";
    
      // Open device file
      std::ifstream disk(diskName, std::ios_base::binary);
    
      if(!disk)
        throw(std::runtime_error(diskError + std::strerror(errno)));
    
      // Seek to 54321'th sector
      disk.seekg(512 * 54321);
      if(!disk)
        throw(std::runtime_error(diskError + std::strerror(errno)));
    
      // Read in one sector
      std::vector buffer(512);
      disk.read(&buffer[0], 512);
      if(!disk)
        throw(std::runtime_error(diskError + std::strerror(errno)));
    }
    

提交回复
热议问题