代码之家  ›  专栏  ›  技术社区  ›  Hubert Gonera

如何在Linux Mint上使用Libparted写出所有连接的设备?

  •  1
  • Hubert Gonera  · 技术社区  · 10 月前

    我一直在尝试在Linux Mint 22 x86_64上使用C++和libparted将所有连接的存储设备打印到我的机器上。

    我一直在修补 ped_device_get_next() 函数,它应该返回由提供的列表中的下一个设备 ped_device_probe_all() 功能。我很难让它工作,因为这个库的文档很差。

    我学到的最有用的东西就是这段简单的代码。

    #include <cmakeconfig.h>
    #include "mainheader.h"
    
    int main()
    {
        ped_device_probe_all();
    
        PedDevice *tempbed;
        int c = 0;
        do {
            tempbed = ped_device_get_next(NULL);
            std::cout<<c<<" "<<tempbed->model<<"\n";
            c++;
        } while(tempbed != NULL && c < 256); 
    
        return 0;
    }
    

    它所做的就是将我的SSD型号打印256次。如果没有c变量作为安全机制,它就会永远这样做(直到资源耗尽)。

    它不会在任何地方打印出我的硬盘型号。

    我知道我的代码完全按照文档所说的那样,打印出第一个设备x次,但我只是不知道如何让它连续打印出设备。

    0 <model name>
    1 <model name>
    2 <model name>
    3 <model name>
    4 <model name>
    etc.
    

    Documentation of ped_device_get_next

    1 回复  |  直到 10 月前
        1
  •  0
  •   Jerry Coffin    10 月前

    您最初调用ped_device_get_next(NULL);然后在后续调用中,传递它在前一次调用中返回的值。一种方法是这样的:

    int main()
    {
        ped_device_probe_all();
    
        PedDevice *tempbed = nullptr;
        int c = 0;
    
        while((tempbed = ped_device_get_next(tempbed))!= nullptr && c <255) {
            std::cout<<c<<" "<<tempbed->model<<"\n";
            c++;
        } 
    
        return 0;
    }
    

    …或者你可以把它包装成一个模仿容器的类:

    #include <parted/parted.h>
    
    
    class devices {
    public:
        class iterator {
            PedDevice *current = nullptr;
        public:
            iterator &operator++() {
                current = ped_device_get_next(current);
                return *this;
            }
    
            PedDevice &operator*() const { return *current; }
    
            bool operator!=(iterator const &other) const { 
                return current != other.current;
            }
        };
        
        devices() { ped_device_probe_all(); }
        iterator begin() {
            iterator i;
            return ++i;        
        }
        iterator end() { return iterator(); }
    };
    

    …然后像其他容器一样迭代它:

    int main()
    {
        devices dev;
    
        for (auto const &d : dev) {
            std::cout << d.model << "\n";
        }
    }
    

    顺便说一句,请注意,在大多数系统上,您必须以root身份运行它才能实际显示任何内容。