问题描述
我从 this post
得到这个代码#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
void main()
{
char* folder="/dev/input"; //folder to open
DIR* dir_p;
struct dirent* dir_element;
struct stat file_info;
// open directory
dir_p=opendir(folder);
// show some info for each file in given directory
while(dir_element = readdir(dir_p)) {
lstat(dir_element->d_name,&file_info); //getting a file stats
puts(dir_element->d_name); // show current filename
printf("file mode: %d\n",file_info.st_mode);
// print what kind of file we are dealing with
if (file_info.st_mode == S_IFDIR) puts("|| directory");
if (file_info.st_mode == S_IFREG) puts("|| regular file");
if (file_info.st_mode == S_IFLNK) puts("|| symbolic link");
if (S_ISCHR(file_info.st_mode)) puts("|| character file");
}
}
我稍微修改了它,以便它打印 /dev/input
中的文件是否为字符文件。但是当我运行它时(即使使用 sudo)它只打印文件名、文件模式而不打印其他任何东西。
解决方法
首先,file_info.st_mode
是位域,因此您应该检查是否使用 &
运算符设置了各个位。
也就是说,
if (file_info.st_mode & S_IFDIR) puts("|| directory");
然而,使用 S_ISXXX
宏比上一个宏更明确。
其次,dir_element->d_name
仅包含路径的基本名称。因此,您应该在将其送入 folder
之前为其添加 lstat
。如果您检查过 lstat
的返回值,您可能知道它没有成功。
所以你可以做类似的事情
// 2 is for '/' and '\0'
char *full_path = malloc(strlen(folder) + strlen(dir_element->d_name) + 2;
// please do check if malloc failed
// I'm sure FULL_PATH has sufficient memory,but use strncpy/strncat if in doubt
strcpy(full_path,folder);
strcat(full_path,"/");
strcat(full_path,dir_element->d_name);
lstat(full_path,&file_info);
free(full_path);