“无法打开文件”,当程序尝试打开/ proc

问题描述:

中的文件时,我尝试使用c程序读取文件/ proc /'pid'/ status。代码如下,即使我使用sudo来运行它,提示仍会一直抛出“无法打开文件”。请让我知道如果你有任何想法如何解决这个问题。感谢“无法打开文件”,当程序尝试打开/ proc

理查德

...

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字符串。你忘了分配这个。 A 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()); 
+0

@tristartom:试过打印'errno'? – Potatoswatter 2010-04-06 04:14:44

您还没有分配的内存供fileLoc

char* fileLoc; // just a char pointer...pointing to some random location. 
. 
. 
sprintf(fileLoc, "/proc/%d/status", atoi(argv[1])); 

指向的字符数组后动态分配的数组和*,或者你可以使用合适大小的静态数组,或者更好地使用C++ string