c++ - "Unable to open file", 当程序试图打开/proc 中的文件时

标签 c++ file-io error-handling

我尝试使用 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/

相关文章:

c++ - Visual C++ 2008 中的 int64_t、int_least16_t 和 uint8_t 等同于什么?

C++无法创建类的实例

c - 处理从库中的 OS API 返回的错误的最佳方法是什么?

c++ - 关于 C++ 中的析构函数;

c++ - (OpenMP) 如何在 1 个线程中启动每个函数 1 次

c++ - 二进制文件的 ifstream 与 fread

java - 如何在 java 中使用 .readLine() 跟踪文件的读取?

java - 如何搜索长度分隔的字典

r - 处理R中的气质错误

error-handling - 无法导入Silhouette Visualizer-几乎尝试了所有操作