将文件列表保存到数组或其他内容中 [英] save file listing into array or something else C
本文介绍了将文件列表保存到数组或其他内容中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个功能
void file_listing(){
DIR *dp;
struct stat fileStat;
struct dirent *ep;
int file=0;
dp = opendir ("./");
if (dp != NULL){
while ((ep = readdir(dp))){
char *c = ep->d_name;
char d = *c; /* first char */
if((file=open(ep->d_name,O_RDONLY)) < -1){
perror("Errore apertura file");
}
if(fstat(file,&fileStat)){ /*file info */
perror("Errore funzione fstat");
}
if(S_ISDIR(fileStat.st_mode)){ /* directory NOT listed */
continue;
}
else{
if(d != '.'){ /* if filename DOESN'T start with . will be listed */
"save into someting" (ep->d_name);
}
else{
continue; /* altrimenti non lo listo */
}
}
}
(void) closedir (dp);
}
else{
perror ("Impossibile aprire la directory");
return 1;
}
}
我想将文件列表的结果保存到数组,结构或列表等中,但是我不知道该怎么做.
预先感谢!
I want to save into an array or a struct or a list or something else the result of file listing but i don't know how to do it.
Thanks in advance!
推荐答案
以下是一个示例函数,该函数将文件列表存储在数组中并返回条目数:
Here is a sample function that stores the file listing in array and returns the number of entries:
#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]);
}
}
请注意,我在目录上进行了两次迭代-第一次获取文件计数,第二次保存结果.如果在执行过程中在目录中添加/删除文件,此操作将无法正常进行.
Note that I iterate twice over the directory - first time to get the files count and second time to save the results. This won't work correctly if you add/remove files in the directory while this is being executed.
这篇关于将文件列表保存到数组或其他内容中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文