c++ - 在C/C++中打开驻留在 “/sys/”下的文件时出错

标签 c++ c linux file io

我无法读取驻留在/sys下的文件(准确地说是/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:01/PNP0C09:00/PNP0C0A:00/power_supply/BAT0/capacity)。我已经尝试使用C方法(fopenfread)和C++方法(std::ifstream)。这是到目前为止我所做的:

//headerfile.h
protected:
    char m_path[150];
    QString m_temp;
    std::string m_temp_str;
    FILE *m_pipePtr;
    std::ifstream m_batPtr;
//Inside a member function definition :
...
    m_pipePtr = popen("find /sys 2>/dev/null | grep \"BAT0/capacity\" | grep -v \"capacity_level\"" , "r");
    if(m_pipePtr == NULL){
        qDebug() << "Cannot read the battery percentage\n" << endl;
        exit(1);
    }
    fgets(m_path , sizeof(m_path) , m_pipePtr);

...

    m_batPtr.open(m_path);
    qDebug() << m_path << endl;      //Path is correct
    m_batPtr >> m_temp_str;
    std::cout << m_temp_str << std::endl;         //Empty
    m_temp = QString::fromStdString(m_temp_str);
    qDebug() << m_temp << endl;      //Empty too
    return m_temp;
我可以对该文件进行cat并返回所需的结果。下面的程序也可以按预期工作(似乎很奇怪,但fread在这里正常但在上面的文件中不能正常工作):
#include <stdio.h>
#include <stdlib.h>
void main(){
    FILE *fp2;
    fp2 = fopen("/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:01/PNP0C09:00/PNP0C0A:00/power_supply/BAT0/capacity" , "r");
    char temp[4];
    fread(temp , 3 , 1 , fp2);
    printf("%s\n" , temp);
    fclose(fp2);
}

怎么了

编辑:的输出:
m_batPtr = fopen(m_path , "r");
std::cout << m_path << std::endl;
Q_ASSERT(m_batPtr);
是:
/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:01/PNP0C09:00/PNP0C0A:00/power_supply/BAT0/capacity

ASSERT: "m_batPtr" in file ../batpercindicator/batperc.cpp, line 18
Aborted (core dumped)
并且在两种情况下(C和C++),问题都是无法打开文件。

最佳答案

m_path可能在末尾包含换行符(\n),因为fgets不会将其删除。用0字节覆盖结尾的第一个换行符。
查找文件名的方法非常难看,并且取决于外部工具。我建议直接在C++代码中搜索文件(可能使用std::filesystem API)

关于c++ - 在C/C++中打开驻留在 “/sys/”下的文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62715363/

相关文章:

c++ - Box2D b2World 类

java - Maven:如何在 Linux 上使用非托管依赖项?

linux - "Program Aborted"但没有返回错误代码

c++ - 打印字符和整数

c++ - D3D - GetSurfaceLevel 未处理的异常

c - 我应该在 .h 文件中定义函数还是只声明它们?

chdir 在 c 代码下的 unix 中不起作用,总是无法更改目录

c - 如何在不使用 for 循环的情况下获取 char * 变量的大小?

linux - arm-linux-gnueabi-gcc 编译的二进制文件不在 ARM 上执行

c++ - 使用 memcpy 重构字符串流的使用