Search code examples
c++linuxposix

How to get source device of mount point in Linux programmatically?


I want to know which device mounted on some directory, like this:

auto device = get_device_of_mount_point("/path/to/some/dir");
std::cout << device << std::endl; // /dev/sda1

Solution

  • Here is a starting point, assuming C++17 is available:

    #include <string_view>
    #include <fstream>
    #include <optional>
    
    std::optional<std::string> get_device_of_mount_point(std::string_view path)
    {
       std::ifstream mounts{"/proc/mounts"};
       std::string mountPoint;
       std::string device;
    
       while (mounts >> device >> mountPoint)
       {
          if (mountPoint == path)
          {
             return device;
          }
       }
    
       return std::nullopt;
    }
    

    You can use this function as follows.

    if (const auto device = get_device_of_mount_point("/"))
       std::cout << *device << "\n";
    else
       std::cout << "Not found\n";