我使用下面的代码将文件名保存到数组中。我从这里得到了代码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]);
}
}
答案 0 :(得分:1)
int i = 0;
while (condition)
{
if (ep->d_name[i] == '.' )
{
++i;
}
//do stuff here
}