Linux系统:
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <dirent.h>
bool hasEnding(std::string const &fullString, std::string const &ending)
{
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
int getFolderFile(const char *path, std::vector<std::string>& files, const char *suffix = ".bin")
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir(path)) != NULL) {
while ((ent = readdir (dir)) != NULL) {
std::string file = ent->d_name;
if(hasEnding(file, suffix)){
files.push_back(file.substr(0, file.length()-4));
}
}
closedir(dir);
} else {
printf("No such folder: %s.", path);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
Windows系统:
#undef UNICODE
#include <windows.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <thread>
#include <filesystem>
int getFolderFile(const char* path, std::vector<std::string>& files, const char* suffix = ".bin")
{
WIN32_FIND_DATA findData;
char filePathName[256];
strcpy(filePathName, path);
strcat(filePathName, "/*");
strcat(filePathName, suffix);
//HANDLE hFind = FindFirstFile((path +"*" + suffix).cstr(), &findData);
HANDLE hFind = FindFirstFile(filePathName, &findData);
if (hFind == INVALID_HANDLE_VALUE)
{
printf("No such folder or no such files: %s\n", path);
return EXIT_FAILURE;
}
do
{
std::string filename = findData.cFileName;
size_t lasDotPos = filename.find_last_of(".");//查找最后一个点号位
if (lasDotPos != std::string::npos)
filename.erase(lasDotPos); //删除从最后一个点号到结尾的部分
files.push_back(filename);
} while (FindNextFile(hFind, &findData) != 0);
FindClose(hFind);
return EXIT_SUCCESS;
}