(一)遍历单层文件夹
//遍历文件夹,并输出文件夹下所有文件
void TraversalFolder(string folderPath)
{
_finddata_t fileInfo;
string fileName = folderPath + "\\*.*";
static char str_time[100];
struct tm *file_create_time = NULL;
// 第一次查找
long fileHandle = _findfirst(fileName.c_str(), &fileInfo);
if(fileHandle == -1L){
cout << "Failed to transfer files!" << endl;
return;
}
//循环查找符合条件的文件
do{
file_create_time = gmtime(&fileInfo.time_create);
strftime(str_time, sizeof(str_time), "%Y-%m-%d,%H:%M:%S", file_create_time);
//输出找到的文件的文件名、创建时间、文件大小
cout << fileInfo.name << " " << str_time << " " << fileInfo.size << endl;
}while( _findnext(fileHandle, &fileInfo)==0 );
_findclose(fileHandle);
}
(二)遍历文件夹及其子文件夹
void dfsFolder(string folderPath)
{
_finddata_t fileInfo;
string strpath = folderPath + "\\*";
long fileHandle = _findfirst(strpath.c_str(), &fileInfo);
if(fileHandle == -1L){
cout << "Can not match the folder path!" << endl;
return;
}
do{
//判断是否存在子目录
if( fileInfo.attrib & _A_SUBDIR ){
if(strcmp(fileInfo.name, ".") && strcmp(fileInfo.name, "..")){
string newpath = folderPath + "\\" + fileInfo.name;
dfsFolder(newpath);
}
}else{
cout << folderPath << "\\" << fileInfo.name << endl;
}
}while( _findnext(fileHandle, &fileInfo)==0 );
_findclose(fileHandle);
}
注:
_finddata_t 为文件信息结构体,用来存储文件的各种信息,头文件引用 #include “io.h”
struct _finddata_t
{
unsigned attrib; //文件属性
time_t time_create; //文件创建时间
time_t time_access; //文件上一次访问时间
time_t time_write; //文件上一次修改时间
_fsize_t size; //文件字节数
char name[_MAX_FNAME]; //文件名
};
文件属性为无符号整数,用位表示,取值为相应的宏:_A_ARCH(存档),_A_SUBDIR(文件夹),_A_HIDDEN(隐藏),_A_SYSTEM(系统),_A_NORMAL(正常),_A_RDONLY(只读)。
time_t是一个变量类型(长整型,相当于long int),用来存储时间,存储的是日历时间,即从一个时间点(例如:1970年1月1日0时0分0秒)到现在的秒数。日历时间可以通过time()函数获取
_MAX_FNAME 是常量宏,定义于头文件中,表示文件名的最大长度。
通过函数_findfirst、_findnext、_findclose将文件信息存储到_finddata_t结构体中,函数原型如下:
//按FileName命名规则匹配当前目录第一个文件
_findfirst(_In_ const char * FileName, _Out_ struct _finddata64i32_t * _FindData);
//按FileName命名规则匹配当前目录下一个文件
_findnext(_In_ intptr_t _FindHandle, _Out_ struct _finddata64i32_t * _FindData);
//关闭_findfirst返回的文件句柄
_findclose(_In_ intptr_t _FindHandle);
struct tm {
int tm_sec; /* 秒 – 取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值等于实际年份减去1900 */
int tm_wday; /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
};
struct tm * gmtime(const time_t *timer); //将日历时间转化为世界标准时间(即格林尼治时间),并返回一个tm结构体来保存这个时间
struct tm * localtime(const time_t * timer); //将日历时间转化为本地时间
strftime (char *s, size_t maxsize, const char *format, const struct tm *tp); //格式化输出函数