我无法读取驻留在/sys
下的文件(准确地说是/sys/devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/device:01/PNP0C09:00/PNP0C0A:00/power_supply/BAT0/capacity
)。我已经尝试使用C方法(fopen
和fread
)和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/