【问题标题】:Listing files in a given directory on Linux在 Linux 上列出给定目录中的文件
【发布时间】:2015-05-10 22:20:54
【问题描述】:

我正在使用scandir() 列出给定目录中的 PNG 图像:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int file_select(const struct dirent *entry)
{
    struct stat st; 
    stat(entry->d_name, &st);
    return (st.st_mode & S_IFREG);       // This doesn't work
    /* return (st.st_mode & S_IFDIR); */ // This lists everything
}
int num_sort(const struct dirent **e1, const struct dirent **e2) {
    char* pch = strtok ((char*)(*e1)->d_name,".");
    char* pch2 = strtok ((char*)(*e2)->d_name,".");
    const char *a = (*e1)->d_name;
    const char *b = (*e2)->d_name;
    return atoi(b) > atoi(a);
}

int main(void)
{
    struct dirent **namelist;
    int n;

    n = scandir(".", &namelist, file_select, num_sort);
    if (n < 0) {
        perror("scandir");/
} else {
    while (n--) {
        printf("File:%s\n", namelist[n]->d_name);
        free(namelist[n]);
    }
    free(namelist);
}
}

问题是上面的代码也列出了:

.
..

我想摆脱它。为此,我使用了:

return (st.st_mode & S_IFREG);

列出所有常规文件。但是,这不会返回任何内容,而 &amp; S_IFDIR 会返回所有内容(即目录 文件)。我该如何解决?

【问题讨论】:

  • 您只需要检查名称字符串。如果是...,则返回false。
  • if( strcmp(namelist[n]-&gt;d_name, ".") &amp;&amp; strcmp(namelist[n]-&gt;d_name, "..") ) printf("File:%s\n", namelist[n]-&gt;d_name); 是你想要的吗?
  • @AndrewMedico 谢谢,但我仍然不明白为什么S_IFREG 不起作用。
  • @BlueMoon 不完全是,但我在file_select() 中添加了类似的内容,因此namelist 将只包含我想要的条目。
  • 我不明白为什么S_IFREG 不应该工作。但这将排除比您想要的更多的文件。您想要的只是排除...,那么一个简单的条件就足够了。 S_IFDIR 也可以使用(如果您想排除所有目录)。

标签: c linux directory scandir


【解决方案1】:

尝试 (st.st_mode & S_IFMT) == S_IFREG。

在与 S_IFREG 进行比较之前,您需要对文件类型位字段执行 & 操作。

还有为这些类型的操作定义的宏,你可以找到here(我也会在下面列出)

       S_ISREG(m)  is it a regular file?

       S_ISDIR(m)  directory?           

       S_ISCHR(m)  character device?

       S_ISBLK(m)  block device?

       S_ISFIFO(m) FIFO (named pipe)?

       S_ISLNK(m)  symbolic link?  (Not in POSIX.1-1996.)

       S_ISSOCK(m) socket?  (Not in POSIX.1-1996.)

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 2016-11-04
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多