C ++读取/ sys / class / net / eth0 / operstate遇到权限被拒绝

问题描述

我必须使用C ++读取嵌入式Linux中以太网接口的状态 我尝试打开并读取文件/sys/class/net/eth0/operstate,但是我观察到fail()成员函数始终返回true,并且errno被拒绝权限。 我的应用程序权限指示器是755,我也尝试将其设置为777,但错误仍然存​​在。

下面是我的代码

int main(int argc,char* argv[])
{   

    std::string word,filename;
    std::fstream ethfile;
    ethfile.open("/sys/class/net/eth0/operstate");

    if (ethfile.fail())
    {
        std::cout << "Error: " << strerror(errno) << '\n';
        return -1;
    }

    ethfile>>word;
    std::cout<<"word is"<<word<<std::endl;
    return 0;
}

编辑:附加信息:这是beaglebone上的yocto。

解决方法

无论您的权限是什么,您都无法打开此特定文件进行写入。

您需要使用ifstream而不是fstream,或指定一种不包括书写的打开模式。