C/C++遍历目录下的所有文件(Windows/Linux)
来源:互联网 发布:excel重复数据统计 编辑:程序博客网 时间:2024/06/01 22:15
1. 遍历目录下的所有文件
#include <iostream>#include <cstring> // for strcat()#include <io.h>using namespace std;void listFiles(const char * dir);int main(){ char dir[200]; cout << "Enter a directory (ends with \'\\\'): "; cin.getline(dir, 200); strcat(dir, "*.*"); // 在要遍历的目录后加上通配符 listFiles(dir); return 0;}void listFiles(const char * dir){ intptr_t handle; _finddata_t findData; handle = _findfirst(dir, &findData); // 查找目录中的第一个文件 if (handle == -1) { cout << "Failed to find first file!\n"; return; } do { if (findData.attrib & _A_SUBDIR && strcmp(findData.name, ".") == 0 && strcmp(findData.name, "..") == 0 ) // 是否是子目录并且不为"."或".." cout << findData.name << "\t<dir>\n"; else cout << findData.name << "\t" << findData.size << endl; } while (_findnext(handle, &findData) == 0); // 查找目录中的下一个文件 cout << "Done!\n"; _findclose(handle); // 关闭搜索句柄}
注意_findnext()函数成功返回0,因此要加上==0或!=-1进行判断,不能省略。
2.遍历目录中的所有文件
#include <iostream>#include <cstring> // for strcpy(), strcat()#include <io.h>using namespace std;void listFiles(const char * dir);int main(){ char dir[200]; cout << "Enter a directory: "; cin.getline(dir, 200); listFiles(dir); return 0;}void listFiles(const char * dir){ char dirNew[200]; strcpy(dirNew, dir); strcat(dirNew, "\\*.*"); // 在目录后面加上"\\*.*"进行第一次搜索 intptr_t handle; _finddata_t findData; handle = _findfirst(dirNew, &findData); if (handle == -1) // 检查是否成功 return; do { if (findData.attrib & _A_SUBDIR) { if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0) continue; cout << findData.name << "\t<dir>\n"; // 在目录后面加上"\\"和搜索到的目录名进行下一次搜索 strcpy(dirNew, dir); strcat(dirNew, "\\"); strcat(dirNew, findData.name); listFiles(dirNew); } else cout << findData.name << "\t" << findData.size << " bytes.\n"; } while (_findnext(handle, &findData) == 0); _findclose(handle); // 关闭搜索句柄}
阅读全文
0 0
- C/C++遍历目录下的所有文件(Windows/Linux)
- C/C++遍历目录下的所有文件(Windows/Linux篇,超详细)
- Linux C :遍历输出指定目录下的所有文件
- Linux C :遍历输出指定目录下的所有文件
- Linux C :遍历输出指定目录下的所有文件
- Linux C :遍历输出指定目录下的所有文件
- Linux C :遍历输出指定目录下的所有文件
- C 语言递归遍历目录下的所有文件
- 通过C/C++遍历目录下的所有文件
- C/C++ 遍历linux目录下所有文件并已树的形式打印
- Linux C :遍历输出指定目录下的所有文件, 及st_mode判断文件类型
- C/C++遍历Windows文件夹下的所有文件
- windows c获取一个目录下的所有文件
- [Linux C]列出指定目录下的所有文件(夹)
- 多目录的Android.mk编写--遍历目录下所有C文件
- c 语言遍历某目录下所有文件代码
- windows遍历目录下所有文件
- windows遍历目录下所有文件
- 红黑树算法原理(从二叉搜索树讲起)
- Python 基础 —— 可变参数 *args 与 关键字参数 **kwargs
- 简单操作的位运算
- JDK源码解析之HashMap
- 20.Scala中本地函数与作为语言一等公民的函数详解
- C/C++遍历目录下的所有文件(Windows/Linux)
- 黑盒测试
- LintCode,Fizz Buzz 问题-java
- 配置管理之持续集成
- kiss rpc flatbuffer,capnp版本和grpc性能测试对比
- (能直接用!)网络监测广播且能自动更新状态,跟着Activity生存周期运作
- ios中多线程的使用
- WebSphere MQ 一些常用的命令
- 时间与时间戳的转换