如何以编程方式获取Linux中的挂载源设备?

问题描述 投票:0回答:1

我想知道某个目录上安装了哪个设备,如下所示:

auto device = get_device_of_mount_point("/path/to/some/dir");
std::cout << device << std::endl; // /dev/sda1
c++ linux posix
1个回答
1
投票

这是一个起点,假设C ++ 17可用:

#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;
}

您可以按如下方式使用此功能。

if (const auto device = get_device_of_mount_point("/"))
   std::cout << *device << "\n";
else
   std::cout << "Not found\n";
© www.soinside.com 2019 - 2024. All rights reserved.