gpt4 book ai didi

c - 列出c目录中的文件

转载 作者:行者123 更新时间:2023-11-30 20:20:22 25 4
gpt4 key购买 nike

我正在使用下面的代码将文件名保存到数组中。我从这里得到了代码save file names to an array 。当我运行这段代码时,它说目录中有 5 个文件(即 count 为 5),但是,只有 3 个。有人可以验证这是否正确,还是我犯了一个严重错误?

#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <malloc.h>

size_t file_list(const char *path, char ***ls) {
size_t count = 0;
size_t length = 0;
DIR *dp = NULL;
struct dirent *ep = NULL;

dp = opendir(path);
if(NULL == dp) {
fprintf(stderr, "no such directory: '%s'", path);
return 0;
}

*ls = NULL;
ep = readdir(dp);
while(NULL != ep){
count++;
ep = readdir(dp);
}

rewinddir(dp);
*ls = calloc(count, sizeof(char *));

count = 0;
ep = readdir(dp);
while(NULL != ep){
(*ls)[count++] = strdup(ep->d_name);
ep = readdir(dp);
}

closedir(dp);
return count;
}

int main(int argc, char **argv) {

char **files;
size_t count;
int i;

count = file_list("/home/rgerganov", &files);
for (i = 0; i < count; i++) {
printf("%s\n", files[i]);
}
}

最佳答案

几个月前,我在一个学校项目中问了自己同样的问题。当您使用 dirent 结构并通过访问元素 d_name 列出它们时,它实际上会计算目录加上“.”。和“..”,所以这是正常的。如果您不想将它们作为目录,只需为循环创建一个迭代器变量并添加如下条件:

int i = 0;
while (condition)
{
if (ep->d_name[i] == '.' )
{
++i;
}
//do stuff here
}

关于c - 列出c目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407021/

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