您的位置:首页 > 编程语言 > C语言/C++

C++下遍历文件夹内文件

2015-12-03 11:27 423 查看
遍历文件夹内文件用到结构体_finddata_t和三个函数:_findfirst, _findnext, _findclose,首先包含头文件:

#include ​“io.h”

结构体_finddata_t的基本信息如下:

​struct _finddata_t

{

unsigned attrib; //文件属性

time_t time_create; //文件创建时间

time_t time_access; //文件上一次访问时间

time_t time_write; //文件上一次修改时间

_fsize_t size; //文件字节数

char name[_MAX_FNAME]; //文件名

};

接下来给出VS2013下的程序源代码,功能是遍历文件夹folder内的txt文件,输出每个文件的文件名和创建时间,并统计txt文件的个数:

#include "stdafx.h"

#include "iostream"

#include "string"

#include "io.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

struct _finddata_t Info;

string strPath = "..\\folder\\*.txt";

int count = 0;

long handle;

//函数_findfirst根据第一个参数提供的路径匹配文件,并将成功匹配的文件

//的信息保存在结构体Info中,同时返回下一个文件的句柄

if ((handle = _findfirst(strPath.c_str(), &Info)) == -1L)

cout << "匹配失败!\n";

cout << Info.name << " 创建时间: " <<Info.time_create<< endl;

count++;

//函数_findnext根据_findfirst返回的句柄,提取该句柄对应文件的信息保存

//在结构体Info中,同时返回下一个文件的句柄

while (!(_findnext(handle, &Info)))

{

cout << Info.name <<" 创建时间: "<<Info.time_create<< endl;

count++;

}

_findclose(handle);

cout << "\n一共" << count << "个txt文件!\n\n";

system("pause");

return 0;

}​

注:源代码中包含头文件需要用尖括号,但尖括号在博客中不能显示,故改为了引号!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: