12

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 access raw disk sectors, but I do not know how to do in in Linux.

I am using GCC on Ubuntu LTS 10.4. Thank you for your help.

3 Answers 3

17

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.

3
  • 3
    /dev/sda1 would be a partition... for raw drive access you'd probably want to use /dev/sda
    – David Z
    Sep 2, 2011 at 21:39
  • +1 for "just another file" and not messing with dd. Be wary of permissions, you'll probably either need to be a member of the disk group or root (not a great idea) to do this.
    – Flexo
    Sep 2, 2011 at 21:41
  • That this will be very helpful.
    – Anthoni C
    Sep 3, 2011 at 0:29
12

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 <fstream>
#include <cerrno>
#include <stdexcept>
#include <cstring>
#include <vector>

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<char> buffer(512);
  disk.read(&buffer[0], 512);
  if(!disk)
    throw(std::runtime_error(diskError + std::strerror(errno)));
}
2
1

you can dump disk sectors to a file with the dd command and read the file generated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.