老实说,我已经有几年没有使用 C++ 了,所以请多多包涵。
我不是要你为我编写这段代码,只是指出我可以在哪里找到解决方案的方向(或者至少是我可以使用的类似的东西)
操作系统: window 使用:dirent.h 不使用:提升
-伪代码
- 开始
- 提示用户输入目录
- 在目录中搜索所有扩展名为 .txt 的文件
- 如果没有文件则出错
- 如果文件那么
- 获取文件并存储列表
- 输出文件列表
- 用这里的文件做其他事情
- 结束
我知道如何接受来自用户的输入,但我不知道如何应用该输入(包含目录路径的字符串)来导航和检查文件。
这是一个工作项目,突然间就被扔到了我的腿上。我将不胜感激。
最佳答案
下面是一些使用 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);
}
关于c++ - 如何在用户提供的目录中查找具有特定扩展名的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19189014/