2010-04-06 173 views
2

中的文件時,我嘗試使用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; 
} 

回答

1

避免在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

1

您還沒有分配的內存供fileLoc

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

指向的字符數組後動態分配的數組和自由,或者你可以使用合適大小的靜態數組,或者更好地使用C++ string