访问要输出的矢量迭代器元素



我对c ++很陌生,我正在尝试创建一个实用程序来查找所有网络设备并列出它们的名称和MAC地址。我已经准备好了要编译的所有内容,但是当我运行to_string()方法时,我没有获得终端的任何输出。我相信我正在访问迭代器对象并错误地调用to_string()

//networkinterfacelist_class.cpp
#include "networkinterfacelist.h"
//get list of network interfaces and push them into a vector list
networkinterfacelist_class::networkinterfacelist_class(){
if ((dir = opendir ("/sys/class/net")) != NULL){
while ((ent = readdir (dir)) != NULL) {
std::string device(ent->d_name);
//skips the parent and current folder
if(device == "." || device == ".."){
continue;
}
dir_list.push_back(device);
}
closedir (dir);
}
}
//iterate through the devices and find their mac addresses
std::vector<networkinterface_class> networkinterfacelist_class::create_device(){
for( std::vector<std::string>::iterator it = dir_list.begin(); it != dir_list.end(); ++it){
if ((dir2 = opendir ("/sys/class/net")) != NULL){
if ((dir = opendir (it->c_str())) != NULL){
//opens the address file saves mac address in line
inFile.open("address");
while(!inFile){
getline(inFile, line);
}
//creates a new networkinterface class and pushes it onto a list
networkinterface_class obj( *it , line);
list.push_back(obj);
}
}
}
return list;
}
//iterates over the list of network devices and prints their name and mac address
void networkinterfacelist_class::to_string(){
for(std::vector<networkinterface_class>::iterator it = list.begin(); it != list.end(); ++it){
(*it).to_string();
}
}

和我的网络接口类

//networkinterface_class.cpp
#include "networkinterface.h"
networkinterface_class::networkinterface_class(std::string device, std::string macaddress){
name = device;
mac = macaddress;
}
std::string networkinterface_class::get_name(){
return name;
}
std::string networkinterface_class::get_mac(){
return mac;
}
void networkinterface_class::to_string(){
std::cout << "Name: " << networkinterface_class::get_name() << "tMAC: " << networkinterface_class::get_mac() << std::endl;
}

任何帮助或提示将不胜感激

您需要定义设备的整个路径。

dir_list.push_back(device); // it pushes only d_name of dirent == filename

在上面的行中,您仅从/sys/class/net推送设备名称,因此当您要读取此设备时,您需要通过将/sys/class/net/与设备名称连接来创建整个路径

if ((dir = opendir ( ("/sys/class/net/" + *it).c_str() )) != NULL){
^^^ get device name as string

而不是

if ((dir = opendir (it->c_str())) != NULL){ // you pass only device without full path

当您要打开文件时,请执行相同的操作address

inFile.open("/sys/class/net/" + *it + "/address");

现在您可以阅读此文件的内容。

最新更新