2010-04-06 5 views
2

C 프로그램을 사용하여/proc/'pid'/ status 파일을 읽으려고합니다. 코드는 다음과 같습니다. 심지어 sudo를 사용하여 실행해도 프롬프트는 여전히 "Unable to open file"을 계속합니다. 이 문제를 해결하는 방법에 대한 아이디어가 있으면 알려 주시기 바랍니다. 감사"파일을 열 수 없습니다", 프로그램이/proc 파일을 열려고 할 때

리처드 당신은 동적 배열을 할당하고 무료로 이상 또는 당신이 할 수있는 fileLoc

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

가 가리키는 문자 배열에 대한 메모리를 할당하지 않은

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 문자열을 사용하지 마십시오. 이 번호를 할당하는 것을 잊었습니다. 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

1

... 적절한 크기의 정적 배열을 사용하거나 C++ string을 더 잘 사용하십시오.

관련 문제