【发布时间】:2016-07-23 15:03:16
【问题描述】:
我将读取 /proc 的每个目录中的“comm”文件。我的程序可以看到目录列表,但是当我尝试打开此目录中的文件夹时出现错误。我的系统是 Debian Linux 硬件 Beaglebone Black。我正在学习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;
}
来自 linux 控制台的日志:
【问题讨论】:
-
此函数失败时,设置errno。添加#include
并将errno值添加到打印中,这样你就知道它为什么失败了