2016-07-23 75 views
-1

我要在/ 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值添加到打印中,這樣您就知道它爲什麼失敗了 –

回答

0

你需要使用的完整路徑打開文件。即:/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