我尝试使用 C 程序读取文件/proc/'pid'/status。代码如下,即使我用sudo运行,提示还是一直抛出“Unable to open file”。如果您对如何解决此问题有任何想法,请告诉我。谢谢
理查德
...
int main (int argc, char* argv[]) {
string line;
char* fileLoc;
if(argc != 2)
{
cout << "a.out file_path" << endl;
fileLoc = "/proc/net/dev";
} else {
sprintf(fileLoc, "/proc/%d/status", atoi(argv[1]));
}
cout<< fileLoc << endl;
ifstream myfile (fileLoc);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
最佳答案
避免在 C++ 中使用 C 字符串。你忘了分配这个。 stringstream
将为您分配并具有 sprintf
功能。
int main (int argc, char* argv[]) {
string line;
ostringstream fileLoc;
if(argc != 2)
{
cout << "a.out file_path" << endl;
fileLoc << "/proc/net/dev";
} else {
fileLoc << "/proc/" << argv[1] << "/status";
}
cout<< fileLoc.str() << endl;
ifstream myfile (fileLoc.str().c_str());
关于c++ - "Unable to open file", 当程序试图打开/proc 中的文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2582524/