gpt4 book ai didi

C - Scandir 只用文件夹填写名单

转载 作者:太空宇宙 更新时间:2023-11-04 07:12:49 27 4
gpt4 key购买 nike

我如何使用 scandir,以便它只用文件夹填充我的 struct dirent ** 名单?

最佳答案

您可以通过提供过滤函数来过滤要列出的实体,如果要将文件包含在列表中,该函数应返回非零值。

不幸的是,dirent 结构的成员不会告诉您您是否有目录(尽管是 your system might include a type field ),因此您必须使用其他方式来查找目录,例如统计:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

int filter_dir(const struct dirent *e)
{
struct stat st;

stat(e->d_name, &st);
return (st.st_mode & S_IFDIR);
}

您也可以尝试调用 opendir 名称并检查是否成功。 (但是如果成功不要忘记关闭它。)

这适用于当前目录,因为名称排除了路径。过滤器也不提供用于传递额外数据的插槽,因此您最好的办法是定义一个全局变量来保存路径并且您必须事先设置该变量。

这是一个带有包装函数的实现,scandir_dir:

#include <stdlib.h>
#include <stdio.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

static const char *filterdir;

static int filter_dir(const struct dirent *e)
{
char buf[NAME_MAX];
struct stat st;

if (filterdir) {
snprintf(buf, sizeof(buf), "%s/%s", filterdir, e->d_name);
stat(buf, &st);
} else {
stat(e->d_name, &st);
}
return (st.st_mode & S_IFDIR);
}

int scandir_dir(const char *path, struct dirent ***namelist)
{
int n;

filterdir = path;
n = scandir(path, namelist, filter_dir, alphasort);
filterdir = NULL;

return n;
}

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

n = scandir_dir("/some/dir", &namelist);

if (n < 0) {
perror("scandir");
} else {
int i;

for (i = 0; i < n; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
}

return 0;
}

关于C - Scandir 只用文件夹填写名单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27023697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com