如何获取目录中的文件列表,以便可以处理每个文件?
这是我使用的:
/* Returns a list of files in a directory (except the ones that begin with a dot) */ void GetFilesInDirectory(std::vector&out, const string &directory) { #ifdef WINDOWS HANDLE dir; WIN32_FIND_DATA file_data; if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE) return; /* No files found */ do { const string file_name = file_data.cFileName; const string full_file_name = directory + "/" + file_name; const bool is_directory = (file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; if (file_name[0] == '.') continue; if (is_directory) continue; out.push_back(full_file_name); } while (FindNextFile(dir, &file_data)); FindClose(dir); #else DIR *dir; class dirent *ent; class stat st; dir = opendir(directory); while ((ent = readdir(dir)) != NULL) { const string file_name = ent->d_name; const string full_file_name = directory + "/" + file_name; if (file_name[0] == '.') continue; if (stat(full_file_name.c_str(), &st) == -1) continue; const bool is_directory = (st.st_mode & S_IFDIR) != 0; if (is_directory) continue; out.push_back(full_file_name); } closedir(dir); #endif } // GetFilesInDirectory
标准C++没有提供这样做的方法.但是boost::filesystem
可以这样做:http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp
这是Linux上的C示例.那就是,如果你在Linux上并且不介意在ANSI C中做这么小的一点.
#includeDIR *dpdf; struct dirent *epdf; dpdf = opendir("./"); if (dpdf != NULL){ while (epdf = readdir(dpdf)){ printf("Filename: %s",epdf->d_name); // std::cout << epdf->d_name << std::endl; } } closedir(dpdf);