我在Linux中有一个C程序,该程序从结构DIR收集目录条目(类型为'struct dirent *'),并显示它们。现在,我的目标是递归地遍历文件系统,因此我需要分别标识Directory和Files。
DIR* cwd = opendir(".");
struct dirent* directoryEntry = NULL;
while((directoryEntry = readdir(cwd)) != NULL){ printf("%s ", directoryEntry->d_name); }
closedir(cwd);
我知道您可以说如果结尾处带有扩展名“ .mp4”或“ .txt”,我们可以识别文件。但是也可能存在没有任何扩展名的文件。
是否有struct dirent *的任何属性,它是文件还是目录?
您可以尝试以下方法:
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Not an offset; see below */
unsigned short d_reclen; /* Length of this record */
unsigned char d_type; /* Type of file; not supported
by all filesystem types */
char d_name[256]; /* Null-terminated filename */
};
并且一旦有了它,检查d_type
是否包含DT_DIR
:
DT_BLK This is a block device.
DT_CHR This is a character device.
DT_DIR This is a directory. <<---- this one!!!
DT_FIFO This is a named pipe (FIFO).
DT_LNK This is a symbolic link.
DT_REG This is a regular file.
DT_SOCK This is a UNIX domain socket.
DT_UNKNOWN The file type could not be determined.
有关其他问题,请参阅http://man7.org/linux/man-pages/man3/readdir.3.html