参考自:C++ Program to Get the List of Files in a Directory
适用于C++ 17的代码如下:
// C++ Program for Getting
// the list of files using
// the directory_iterator function
#include <filesystem>
#include <iostream>
#include <string>
#include <sys/stat.h>
#include <cstring>
namespace fs = std::filesystem;
void ChangePath(const char * path) // 提出新的文件存放路径
{
char oldfile[100], Newfile[100] ;
memset(oldfile, '\0', 100) ;
memset(Newfile, '\0', 100) ;
strcpy(oldfile, "D:\\File\\") ;
strcpy(Newfile, "D:\\NewFile\\") ;
for (int i=20; i<strlen(path); i++)
{
oldfile[20+(i-20)] = path[i] ;
Newfile[11+(i-20)] = path[i] ;
}
std::cout << "oldfile: " << oldfile << std::endl;
std::cout << "newfile: " << Newfile << std::endl;
}
int main()
{
// Path to the directory
std::string path
= "D:\\FileToEncryption";
// This structure would distinguish a file from a
// directory
struct stat sb;
// Looping until all the items of the directory are
// exhausted
for (const auto& entry : fs::directory_iterator(path)) {
// Converting the path to const char * in the
// subsequent lines
std::filesystem::path outfilename = entry.path();
std::string outfilename_str = outfilename.string();
const char* path = outfilename_str.c_str();
// Testing whether the path points to a
// non-directory or not If it does, displays path
if (stat(path, &sb) == 0 && !(sb.st_mode & S_IFDIR))
std ::cout << "old:"<< " " << path << std::endl;
ChangePath(path) ;
}
}
更新:又找到了一种新的遍历文件夹文件的方法,适用于C++ 11:
参考: C++ How to search a folder
Members of Dirent structure
#include <iostream>
#include <dirent.h>
#include <cstring>
using namespace std;
void ChangePath(char * path)
{
char oldfile[100] ;
char newfile[100] ;
memset(oldfile, '\0', 100) ;
memset(newfile, '\0', 100) ;
strcpy(oldfile, "D:\\FileToEncryption\\") ;
strcpy(newfile, "D:\\NewFile\\") ;
strcat(oldfile, path) ;
strcat(newfile, path) ;
cout << "oldfile: " << oldfile << endl ;
cout << "newfile: " << newfile << endl ;
}
int main(void)
{
DIR *dir = opendir("D:\\FileToEncryption"); // 遍历此文件夹
if(dir)
{
struct dirent *ent;
while((ent = readdir(dir)) != NULL)
{
if ((strcmp(ent->d_name, ".")) && (strcmp(ent->d_name, "..")))
ChangePath(ent->d_name);
}
}
else
{
cout << "Error opening directory" << endl;
}
return 0;
}
该程序运行后所遍历出的ent->d_name是文件名,并不是完整的文件路径。
更新: 想用Python遍历怎么办?
参考:Python – List Files in a Directory
使用第二段代码时可能会出现: “dirent.h”: No such file or directory
具体参考: VS2017/2019 无法打开包括文件: “dirent.h”: No such file or directory