C_fileGet.c
#include "C_fileGet.h"
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
C_dirFileSave* C_dirFileSave_INIT()
{
C_dirFileSave* new_node = (C_dirFileSave*)malloc(sizeof(C_dirFileSave));
if(new_node == NULL)
{
return NULL;
}
new_node->next = NULL;
memset(new_node->fileName,'\0',100);
return new_node;
}
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 == 8)
{
C_dirFileSave* new_node = C_dirFileSave_INIT();
strcpy(new_node->fileName,ptr->d_name);
new_node->type = ptr->d_type;
new_node->next = head->next;
head->next = new_node;
}
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);
}
}
}
//如果把函数改成这个的话,可以保留文件相对于传入文件夹的路径
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 == 8)
{
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;
}
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);
}
}
}
C_fileGet.h
#ifndef _CONE_LY_C_FILE_GET_H
#define _CONE_LY_C_FILE_GET_H
typedef struct _C_DIR_FILE_SAVE{
int type;
char fileName[100];
struct _C_DIR_FILE_SAVE* next;
}C_dirFileSave;
C_dirFileSave* C_dirFileSave_INIT();
int C_DIR_read(char*path,C_dirFileSave* head);
#endif/*_CONE_LY_C_FILE_GET_H*/
main.c
#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);
}
}
以后可能会用的上,记录一份