无法在C linux中的/ proc位置打开文件夹

无法在C linux中的/ proc位置打开文件夹

问题描述:

我要在/ proc的每个目录中读取“comm”文件。我的程序可以看到目录列表,但是当我尝试在此目录中打开文件夹时,出现错误。我的系统是Debian Linux硬件Beaglebone Black。我在linux下学习编程,所以我有很多问题(有时候很愚蠢)。无法在C linux中的/ proc位置打开文件夹

的代码清单:从Linux控制台

#include <stdlib.h> 
#include <stdio.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <dirent.h> 

#include <string.h> 
#include <fcntl.h> 

int main() 
{ 
    char path[50] = {0}; 
    register struct dirent *dirbuf; 
    char* dirname = "/proc"; 
    DIR *fdir; 

    fdir = opendir(dirname); 
    if (NULL == fdir) 
    { 
     printf("Can't open %s\n", dirname); 
     return; 
    } 

    while((dirbuf = readdir(fdir)) != NULL) 
    { 
     if ((strcmp(dirbuf->d_name, ".") == 0)||(strcmp(dirbuf->d_name, "..") == 0)) 
     { 
      continue; 
     } 

     printf("folder name: %s\n", dirbuf->d_name); 
     strcat(path, dirbuf->d_name); 
     strcat(path, "/comm"); 
     printf("path: %s\n", path); 

     int fd = open(path, O_RDONLY); 
     if (-1 == fd) 
     { 
      printf("Can't open file %s\n", path); 
     } 
     else 
     { 
      //read file 
      close(fd); 
     } 
     memset(path, 0, strlen(path) + 1); //clear path buffer 

    } 
    closedir(fdir); 
    return 0; 
} 

登录:

enter image description here

+0

当此功能失败时,设置errno。添加#include 并将errno值添加到打印中,这样您就知道它为什么失败了 –

你需要使用的完整路径打开文件。即:/proc/PID/comm而不是PID/comm

您可以使用这样的格式化路径:

char* path[PATH_MAX]; 
snprintf(path, PATH_MAX, "/proc/%s/comm", dirbuf->d_name); 

要适当地格式化的路径。

+0

谢谢!还有一个问题。由于dirbuf-> d_name没有\ 0(字符串结尾),因此我需要手动添加“/ proc /%s/comm”路径末尾的\ 0。 – Nemo

+0

对不起,我发现路径默认会有\ 0。 – Nemo

+0

不,你不知道。 ''snprintf''为你增加''0''。详情请见'man snprintf'' – yadutaf