下面是一些使用 dirent.h 遍历目录的示例代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <dirent.h>
using namespace std;
bool has_suffix(const string& s, const string& suffix)
{
return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
int main(int argc, char **argv)
{
cout << "Directory name: ";
string path;
getline(cin, path);
DIR *dir = opendir(path.c_str());
if(!dir)
{
return 1;
}
dirent *entry;
while((entry = readdir(dir))!=null)
{
if(has_suffix(entry->d_name, ".txt"))
{
cout << entry->d_name << endl;
}
}
closedir(dir);
}