繁体   English   中英

如何通过编程获取Linux中安装点的源设备?

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

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

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 found\n";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM