c/c++ 获取目录下文件列表
2016-07-15 10:09
453 查看
经过测试 Windows 和 Linux版本都可以运行。
关键函数:_findfirst、_findnext
关键结构体:_finddata_t
代码
linux版本
windows版本
头文件:io.h关键函数:_findfirst、_findnext
关键结构体:_finddata_t
struct _finddata_t { unsigned attrib; //_A_ARCH(存档) //_A_HIDDEN(隐藏) //_A_NORMAL(正常) //_A_RDONLY(只读) //_A_SUBDIR(文件夹) //_A_SYSTEM(系统) time_t time_create; //创建日期 time_t time_access; //最后访问日期 time_t time_write; //最后修改日期 _fsize_t size; //文件大小 char name[_MAX_FNAME]; //文件名, _MAX_FNAME表示文件名最大长度 };
代码
#include <iostream> #include <string> #include <io.h> using namespace std; void dir(string path) { long hFile = 0; struct _finddata_t fileInfo; string pathName, exdName; // \\* 代表要遍历所有的类型,如改成\\*.jpg表示遍历jpg类型文件 if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) { return; } do { //判断文件的属性是文件夹还是文件 cout << fileInfo.name << (fileInfo.attrib&_A_SUBDIR ? "[folder]" : "[file]") << endl; } while (_findnext(hFile, &fileInfo) == 0); _findclose(hFile); return; } int main() { //要遍历的目录 string path = "E:\\intel_tuyoji_pic\\群贤"; dir(path); system("pause"); return 0; }
linux版本
#include<iostream> #include<string> #include<dirent.h> using namespace std; int main() { string dirname; DIR *dp; struct dirent *dirp; cout << "Please input a directory: "; cin >> dirname; if((dp = opendir(dirname.c_str())) == NULL) { cout << "Can't open " << dirname << endl; } while((dirp = readdir(dp)) != NULL) { cout << dirp->d_name << endl; } closedir(dp); return 0; }
相关文章推荐
- 关于栈、堆、静态变量区的访问效率
- 关于指针定义的一些问题
- 关于C++ 11的新特性
- 进制转换并打印
- 函数指针
- C/C++的字符串流
- c/c++的笔记(看到想记录的就添加)
- MinGW环境变量设置、CodeBlock添加额外的库
- NodeJS C/C++扩展之Hello World~
- websocket C/C++服务器应用
- 内存分配学习(一)-- 实现一个malloc
- 逗号运算符与加加减减
- C/C++ struct 成员对齐
- C/C++数据类型总结
- 数组初始化
- C/C++中的回车与换行
- C/C++中的'\0'
- #define do{}while(0)妙用
- 浅析pragma once与include guard
- 大小端模式