要求:
1.做一个动态库,提供一个接口。返回某个文件目录下的指定后缀名文件路径链表,不包括子目录。如.pdf;.docx格式。
2.数据结构格式:
typedef struct TargetFile TargetFile; struct TargetFile { char* path; TargetFile* next; TargetFile* previous; };
read_config.h
typedef struct TargetFile TargetFile; struct TargetFile { char* path; TargetFile* next; TargetFile* previous; }; int GetAllfile(const char* path, const char* file_suffix, TargetFile* root_node); int FreeList(TargetFile* head_node);
read_config.cpp
char *strrstr(const char *s, const char *str) { char *p; int len = strlen(s); for (p = const_cast<char*>(s + len - 1); p >= s; p--) { if (*p == *str) return p; } return NULL; } int GetAllfile(const char* path, const char* file_suffix, TargetFile* root_node) { TargetFile* curr_node = root_node; struct dirent* ent = NULL; DIR* pDir; pDir=opendir(path); while(NULL != (ent=readdir(pDir))) { if (!strcmp(ent->d_name, "..") || !strcmp(ent->d_name, ".") || _A_SUBDIR == pDir->dd_dta.attrib) { continue; } char* curr_file_suffix = strrstr(ent->d_name, "."); if(!(strcmp(file_suffix, curr_file_suffix))) { TargetFile* one_node = (TargetFile*) malloc(sizeof(TargetFile)); memset(one_node, 0, sizeof(TargetFile)); int len = strlen(path) + strlen(ent->d_name) + 1; one_node->path = (char*)malloc(len); memset(one_node->path, 0, sizeof(len)); strcpy(one_node->path, path); strcat(one_node->path, ent->d_name); curr_node->next = one_node; one_node->previous = curr_node; curr_node = one_node; } } closedir(pDir); return 0; } int FreeList(TargetFile* head_node) { TargetFile* node1 = head_node; TargetFile* node2 = head_node; while(node1) { node2 = node1->next; free(node1->path); free(node1); node1 = node2; } return 0; }
test
int main() { TargetFile* root_node = (TargetFile*) malloc(sizeof(TargetFile)); memset(root_node, 0, sizeof(TargetFile)); GetAllfile("E:/cppguide/", ".pdf", root_node); TargetFile* node = root_node->next; while(node) { cout<<node->path<<endl; node = node->next; } FreeList(root_node); return 0; }