I try to read file /proc/'pid'/status, using c program. The code is as follows, and even I use sudo to run it, the prompt still keeps throwing "Unable to open file". Please let me know if you have any ideas on how to fix this. thanks
Richard
...
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开发者_如何学Python (fileLoc);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Avoid using C strings in C++. You forgot to allocate this one. A stringstream
will allocate for you and has sprintf
functionality.
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());
You have not allocated memory for the char array pointed by fileLoc
char* fileLoc; // just a char pointer...pointing to some random location.
.
.
sprintf(fileLoc, "/proc/%d/status", atoi(argv[1]));
Allocate the array dynamically and free it later or you can use a static array with suitable size or even better use the C++ string
.
精彩评论