【问题标题】:How to identify which entries are files and which are directories in C如何在 C 中识别哪些条目是文件,哪些是目录
【发布时间】:2020-04-03 13:18:30
【问题描述】:

我在 Linux 中有一个 C 程序,它从结构 DIR 收集目录条目(类型为“struct dirent*”)并显示它们。现在,我的目标是递归遍历文件系统,所以我需要分别识别 DirectoriesFiles

DIR* cwd = opendir(".");
struct dirent* directoryEntry = NULL;
while((directoryEntry = readdir(cwd)) != NULL) {
    printf("%s ", directoryEntry->d_name);
}
closedir(cwd);

我知道你可以说如果文件末尾有一些扩展名“.mp4”或“.txt”,我们可以识别文件。但也可能存在没有任何扩展名的文件。

struct dirent*有没有属性可以判断是文件还是目录?

【问题讨论】:

标签: c linux unix operating-system ls


【解决方案1】:

你可以试试这个:

   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

【讨论】:

  • 你能确定哪个文件系统不支持这个吗?
  • @AliSajjad 您能否查看我在答案中列出的手册页,它有文件系统列表。
猜你喜欢
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
相关资源
最近更新 更多