系统平台:windows 7
开发工具:qt creator
测试代码:
/********** * C语言读取目录列表的几种方法 **********/ #include <stdio.h> #include <stdlib.h> #include <io.h> #include <dirent.h> //方法一,通过io.h读取 void ioType(char dirPath[255]){ long file; struct _finddata32i64_t find; chdir(dirPath); file = _findfirst32i64("*.*", &find); if(file == -1L){ printf("空目录!"); exit(0); } printf("%s\n", find.name); while (_findnext32i64(file, &find) == 0) { printf("%s\n", find.name); } _findclose(file); } //方法二,通过系统命令读取 void systemType(char dirPath[255]){ char cmd[30] = "DIR "; //这里将/转换为\,不然dos系统下会报错 for(unsigned int i=0; i<strlen(dirPath); i++){ if(dirPath[i] == '/'){ dirPath[i] = '\\'; } } system(strcat(cmd, dirPath)); } //方法三、通过dirent.h读取 void direntType(char filePath[255]){ DIR *dir = nullptr; struct dirent *entry; dir = opendir(filePath); if(dir == nullptr){ printf("打开目录失败"); exit(0); }else{ while ((entry=readdir(dir)) != nullptr) { printf("%s\n", entry->d_name); } closedir(dir); } } int main(){ printf("请输入文件目录路径:"); char dirPath[255]; scanf("%s", &dirPath); printf("===========================\n"); printf("通过IO方式展示:\n"); printf("===========================\n"); ioType(dirPath); printf("===========================\n"); printf("\n\n通过system调用展示:\n"); printf("===========================\n"); systemType(dirPath); printf("===========================\n"); printf("\n\n通过dirent调用展示:\n"); printf("===========================\n"); direntType(dirPath); return 0; }
效果如下图:
版权声明:
此文为本站源创文章[或由本站编辑从网络整理改编],
转载请备注出处:
[狂码一生]
https://www.sindsun.com/articles/16/132
[若此文确切存在侵权,请联系本站管理员进行删除!]
--THE END--