我要在/ 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;
}
登錄:
當此功能失敗時,設置errno。添加#include並將errno值添加到打印中,這樣您就知道它爲什麼失敗了 –