0

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
Pavel
  • 277
  • 2
  • 13
  • Maybe this will help: [Linux function to get mount points](https://stackoverflow.com/questions/9280759/linux-function-to-get-mount-points) – sebastian Mar 14 '19 at 10:25
  • I guess the first question should be how would you do it from the command line; and you can then implement that answer. Also. C tag is for C; C++ is for C++. – UKMonkey Mar 14 '19 at 10:37
  • Please show the relevant code and state the exact error. Also see [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – jww Mar 15 '19 at 03:22

1 Answers1

1

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";
lubgr
  • 37,368
  • 3
  • 66
  • 117