如何以编程方式在Linux中获取安装点的源设备

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

本文关键字:安装 获取 编程 方式 Linux      更新时间:2023-10-16

我想知道安装在某些目录上的哪个设备,例如:

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

这是一个起点,假设有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 foundn";