C 语言递归获取目录下文件_C-Onely的博客-CSDN博客
在上述博客的基础上,加一个内存释放:
#include "C_fileGet.h"
#include <stdio.h>
int main(int _INPUT_NUMBER,char**_INPUT_STRING)
{
C_dirFileSave* head = C_dirFileSave_INIT();
C_DIR_read(*(_INPUT_STRING+1),head);
C_dirFileSave* get_head = head->next;
for(;get_head!=NULL;get_head = get_head->next)
{
printf("file:[%s]\n",get_head->fileName);
}
//free node
while (head) {
C_dirFileSave* del_head = head;
head = head->next;
free(del_head);
del_head = NULL;
}
}
加一个closedir
//如果把函数改成这个的话,可以保留文件相对于传入文件夹的路径
int C_DIR_read(char*path,C_dirFileSave* head)
{
if(head == NULL)
return -1;
char get_path[1024];
memset(get_path,'\0',1024);
strcpy(get_path,path);
DIR* dir;
struct dirent* ptr;
dir = opendir(get_path);
if(dir == NULL)
{
printf("\nopen [%s] failed\n",get_path);
return -1;
}
while((ptr = readdir(dir)) != NULL)
{
if(strcmp(ptr->d_name,"..") && strcmp(ptr->d_name,".") && ptr->d_type == 4)
{
strcat(get_path,"/");
strcat(get_path,ptr->d_name);
C_DIR_read(get_path,head);
memset(get_path,'\0',1024);
strcpy(get_path,path);
} else {
if(strcmp(ptr->d_name,"..") && strcmp(ptr->d_name,".") )
{// 读取需要的文件,可自己调整选择条件
C_dirFileSave* new_node = C_dirFileSave_INIT();
strcpy(new_node->fileName,get_path);
strcat(new_node->fileName,"/");
strcat(new_node->fileName,ptr->d_name);
new_node->type = ptr->d_type;
new_node->next = head->next;
head->next = new_node;
}
}
}
closedir(dir);
}