获取某个目录下特定格式文件列表[2]_mac版本
2012-12-19 20:26
357 查看
//下面是mac环境下获取某个目录下特定后缀名文件列表,如果要windows代码请看另外一编文章
////file_filtor.h
//file_filtor.cpp
//main.cpp
////file_filtor.h
#ifndef FILE_FILTOR_H #define FILE_FILTOR_H #ifdef __cplusplus extern "C" { #endif typedef struct TargetFile TargetFile; struct TargetFile { char* path; TargetFile* next; TargetFile* previous; }; TargetFile *GetFileFromDir(const char *dir, const char *postfix); void DelTargetFileList(TargetFile *target); #ifdef __cplusplus } #endif #endif /* FILE_FILTOR_H */
//file_filtor.cpp
#include <dirent.h> #include <iostream> #include <stdlib.h> #include <string.h> #include <string> #include "file_filtor.h" TargetFile *GetFileFromDir(const char *path, const char *postfix) { DIR *dir; dir = opendir(path); if (!dir) { return NULL; } std::string str_file_dir = path; if (str_file_dir[str_file_dir.size()-1] != '/') { str_file_dir.append("/"); } TargetFile *head = (TargetFile *)malloc(sizeof(TargetFile)); memset(head, 0, sizeof(TargetFile)); TargetFile *last_file = head; dirent *file_dir = NULL; while(NULL != (file_dir = readdir(dir))) { if (!file_dir || (!strcmp(file_dir->d_name, ".")) || (!strcmp(file_dir->d_name, ".."))) { continue; } if (DT_DIR == file_dir->d_type) { //是目录就继续循环 continue; } //获取后缀 std::string str_postfix = file_dir->d_name; std::string::size_type pos = str_postfix.find_last_of("."); if (std::string::npos == pos) { continue; } str_postfix = str_postfix.substr(pos); if (str_postfix != postfix) { continue; } TargetFile *cur_file = (TargetFile *)malloc(sizeof(TargetFile)); memset(cur_file, 0, sizeof(TargetFile)); std::string str_file_path = str_file_dir + file_dir->d_name; cur_file->path = (char *)malloc(str_file_path.size() + 1); strcpy(cur_file->path, str_file_path.c_str()); cur_file->path[str_file_path.size()] = '\0'; cur_file->previous = last_file; last_file->next = cur_file; last_file = cur_file; } //end while closedir(dir); //去除head结点 TargetFile *ret = head->next; ret->previous = NULL; free(head); return ret; } void DelTargetFileList(TargetFile *target) { if (!target) { return ; } TargetFile *next = target; while (next) { TargetFile *cur = next; next = next->next; if (cur->path) { free(cur->path); } } }
//main.cpp
#include "file_filtor.h" int main(int argc, char** argv) { TargetFile *ret = GetFileFromDir("/usr/resource/pdf", ".pdf"); TargetFile *next = ret; while(next) { std::cout<<next->path<<std::endl; next = next->next; } DelTargetFileList(ret); return 0; }
相关文章推荐
- 获取某个目录下特定格式文件列表
- dos获取目录下文件列表
- python 获取文件列表(或是目录例表)
- ORACLE获取操作系统目录下文件列表
- oracle 获取操作系统目录下文件列表
- Android 按照日期从旧到新获取目录下文件列表
- 获取某一个目录中的所有文件列表
- C语言获取目录下目录&文件列表
- Android获取手机内置外置存储文件列表,完美解决各种rom各种系统版本的获取方式不用的问题
- Linux下获取目录下的文件列表,并按字符串排序
- python获取指定目录下特定格式的文件名
- C/C++ 获取目录下的文件列表信息
- 【Linux】获取指定目录下文件列表
- java实现ftp连接、登陆、上传、下载、删除文件、获取目录、文件列表
- C/C++--C++获取目录下的文件列表
- C# 目录操作(新建,删除),获取目录下文件列表
- python 获取文件列表(或是目录例表)
- C#学习之获取某个文件下的目录列表及子目录列表
- ios中如何用一个格式获取多个文件目录中的全部文件
- Java编程获取文件列表及子文件目录的方法(非递归)