如何使用C 打开目录
How to open a Directory with C++
本文关键字:何使用 更新时间:2023-10-16
我是C 的新手,对于我的第一个任务,我被要求打开一个目录(及其所有子目录(,而仅存储.txt文件路径。这就是我到目前为止所做的,但是我遇到了多个错误。谁能帮忙?
#include<stdio.h>
#include<sys/stat.h>
#include<iostream>
#include<string.h>
#include<string>
#include<dirent.h>
using namespace std;
void explore(char *dir_name){
DIR *dir; // pointer to directory
struct dirent *entry; // all stuff in the directory
struct stat info; // info about each entry
dir = opendir(dir_name);
if (!dir)
{
cout << "Directory not found" << endl;
return;
}
while ((entry = readdir(dir)) != NULL)
{
if (entry->d_name[0] != '.')
{
string path = string(dir_name) + "/" + string(entry->d_name);
cout << "Entry = " << path << endl;
stat(path,&info) //
if (S_ISDIR(info.st_mode))
{
explore(path);
}
}
}
closedir(dir);
}
int main{
explore(".");
return 0;
}
您在Linux上吗?你为什么让事情复杂化?有一种叫做"文件树步行"的东西,可以用最小的努力来完成您想要的事情。这是一个快速示例。有关输入参数的更多信息,请执行man ftw
。
#include <iostream>
#include <ftw.h>
#include <fnmatch.h>
static int explore( const char *fpath,
const struct stat *sb,
int typeflag )
{
if (typeflag == FTW_F) ///< it's a file
{
if (fnmatch("*.txt", fpath, FNM_CASEFOLD) == 0) ///< it's a .txt file
{
std::cout << "found txt file: " << fpath << std::endl;
}
}
return 0;
}
int main()
{
ftw(".", explore, 8);
return 0;
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何确定我已使用非编码文件到达 EOF?
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 使用CMake创建QML插件
- 使用 LLVM 的 libc++ 时,__1 符号从何而来?
- 在std::cout之后使用std::cin时,换行符从何而来
- 为什么以及在何处在C++中使用引用和指针
- 基例如何影响使用递归函数的哪些行