怎么用c语言实现遍历某目录或文件夹里的所有文件(所有类型的文件)?

您所在的位置:网站首页 c语言读取文件所有内容 怎么用c语言实现遍历某目录或文件夹里的所有文件(所有类型的文件)?

怎么用c语言实现遍历某目录或文件夹里的所有文件(所有类型的文件)?

2023-04-06 02:36| 来源: 网络整理| 查看: 265

列目录不是一个C语言标准库支持的操作(类似的操作还有:移动光标等),C++里比较新的规范(C++17)支持filesystem这个库,可以实现语言级别的操作,但C语言没有类似的库。

对于Windows来说,可以使用FindFirstFile+FindNextFile+FindClose这三个API实现遍历动作,详细的用法可以参考MSDN:

以下代码采用VS2019编译,使用多字节方式编码(非unicode):

#define _CRT_SECURE_NO_WARNINGS #include #include #include #include // Recursive是1表示递归查找,否则就只列出本级目录 int ListDirectory(char* Path, int Recursive) { HANDLE hFind; WIN32_FIND_DATA FindFileData; char FileName[MAX_PATH] = { 0 }; int Ret = -1; strcpy(FileName, Path); strcat(FileName, "\\"); strcat(FileName, "*.*"); // 查找第一个文件 hFind = FindFirstFile(FileName, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { printf("Error when list %s\n", Path); return Ret; } do { // 构造文件名 strcpy(FileName, Path); strcat(FileName, "\\"); strcat(FileName, FindFileData.cFileName); printf("%s\n", FileName); // 如果是递归查找,并且文件名不是.和..,并且文件是一个目录,那么执行递归操作 if (Recursive != 0 && strcmp(FindFileData.cFileName, ".") != 0 && strcmp(FindFileData.cFileName, "..") != 0 && FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { ListDirectory(FileName, Recursive); } // 查找下一个文件 if (FindNextFile(hFind, &FindFileData) == FALSE) { // ERROR_NO_MORE_FILES 表示已经全部查找完成 if (GetLastError() != ERROR_NO_MORE_FILES) { printf("Error when get next file in %s\n", Path); } else { Ret = 0; } break; } } while (TRUE); // 关闭句柄 FindClose(hFind); return Ret; } int main() { char Path[MAX_PATH + 1] = { 0 }; // 因为gets在VS2019里不可用,所以用fgets替代 fgets(Path, sizeof(Path), stdin); // 因为使用了fgets,所以要取掉结尾多余的换行符 while (Path[strlen(Path) - 1] == '\n' || Path[strlen(Path) - 1] == '\r') { Path[strlen(Path) - 1] = '\0'; } ListDirectory(Path, 1); return 0; }

执行效果:

Linux使用opendir+readdir+closedir的组合实现(注:Windows也可以用类似API,但效果不太好),相关API行为参见:

参考代码(环境Fedora33自带的gcc),代码逻辑与Windows基本类似:

#include #include #include #include #include int list_dir(char * path, int recursive) { DIR * p_dir; struct dirent * entry; size_t len; char * sub_path; p_dir = opendir(path); if (p_dir == NULL) { printf("Can not open %s/n", path); return -1; } while((entry = readdir(p_dir)) != NULL) { len = strlen(path) + strlen(entry->d_name) + 3; sub_path = calloc(len, 1); if (sub_path == NULL) { printf("out of memory/n"); closedir(p_dir); return -1; } strcpy(sub_path, path); strcat(sub_path, "/"); strcat(sub_path, entry->d_name); printf("%s\n", sub_path); if (entry->d_type == DT_DIR && recursive != 0 && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { list_dir(sub_path, recursive); } free(sub_path); } closedir(p_dir); return -1; } int main() { char path[1024]; gets(path); list_dir(path, 1); return 0; }

没有苹果本,所以不清楚Mac的环境,用Linux的应该是可以的。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3