c++如何查找一个文件目录下所有文件?
认证高级PHP讲师
#include <dirent.h> #include <stdio.h> #include <string.h> int main() { struct dirent *ent = NULL; DIR *dir = opendir("/tmp"); if (dir != NULL) { while ((ent = readdir (dir)) != NULL) { if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0) { printf("%s\n", ent->d_name); } } closedir(dir); return 0; } else { printf("Failed to open directory\n"); return -1; } }
Give me an implementation under windows:
#include <cstdio> #include <cstdlib> #include <cstring> #include <windows.h> #include "io.h" using namespace std; char path[1000]; int len_path=0; void get_info() { path[len_path]='*',path[len_path+1]='rrreee'; _finddatai64_t fileinfo; intptr_t handle=_findfirsti64(path,&fileinfo); if(handle==-1) return; while(!_findnexti64(handle,&fileinfo)) { char *name=fileinfo.name; if(strcmp(name,".")==0||strcmp(name,"..")==0) continue; if(fileinfo.attrib&_A_SUBDIR)//递归子目录 { int n=strlen(name); memcpy(path+len_path,name,n),len_path+=n; path[len_path++]='\'; get_info(); len_path-=n+1; } else puts(fileinfo.name); } _findclose(handle); } int main() { strcpy(path,"D:\"); len_path=strlen(path); get_info(); }
I have also written this before: district10/FindFilesWithinFolder: Find and generate a file list of the folder..
Effect:
➜ build git:(master) ✗ ./FindFilesWithinFolder CMakeFiles CMakeFiles/CMakeDirectoryInformation.cmake CMakeFiles/Makefile2 CMakeFiles/progress.marks CMakeFiles/TargetDirectories.txt CMakeFiles/Makefile.cmake CMakeFiles/cmake.check_cache CMakeFiles/CMakeOutput.log CMakeFiles/3.0.2/CMakeDetermineCompilerABI_CXX.bin CMakeFiles/3.0.2/CMakeCCompiler.cmake CMakeFiles/3.0.2/CMakeDetermineCompilerABI_C.bin CMakeFiles/3.0.2/CMakeSystem.cmake CMakeFiles/3.0.2/CMakeCXXCompiler.cmake CMakeFiles/FindFilesWithinFolder.dir/link.txt CMakeFiles/FindFilesWithinFolder.dir/main.cpp.o CMakeFiles/FindFilesWithinFolder.dir/CXX.includecache CMakeFiles/FindFilesWithinFolder.dir/cmake_clean.cmake CMakeFiles/FindFilesWithinFolder.dir/DependInfo.cmake CMakeFiles/FindFilesWithinFolder.dir/FindFiles.cpp.o CMakeFiles/FindFilesWithinFolder.dir/depend.make CMakeFiles/FindFilesWithinFolder.dir/depend.internal CMakeFiles/FindFilesWithinFolder.dir/progress.make CMakeFiles/FindFilesWithinFolder.dir/build.make CMakeFiles/FindFilesWithinFolder.dir/flags.make CMakeFiles/3.0.2/CompilerIdC/a.out CMakeFiles/3.0.2/CompilerIdC/CMakeCCompilerId.c CMakeFiles/3.0.2/CompilerIdCXX/CMakeCXXCompilerId.cpp CMakeFiles/3.0.2/CompilerIdCXX/a.out
Give me an implementation under windows:
I have also written this before: district10/FindFilesWithinFolder: Find and generate a file list of the folder..
Effect: