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

c++关于文件夹(文件)的相关操作_findfirst,_findnext和_findclose方法

2015-09-16 11:12 573 查看
获取windows下某文件下的所有文件,立即应用。

【说明】可以找到某文件下的任意类型的子文件夹和任意格式的文件,根据”*“来进行任意字符串的替代。

#include <iostream>
#include <string>
#include <io.h>
using namespace std;

void main()
{
_finddata_t file;
long longf;
string tempName;
//_findfirst返回的是long型; long __cdecl _findfirst(const char *, struct _finddata_t *)
if ((longf = _findfirst("d://*.*", &file)) == -1l)
{
cout << "文件没有找到!/n";
return;
}
do
{
cout << "/n文件列表:/n";
tempName = file.name;
if (tempName[0] == '.')
continue;
cout << file.name;

if (file.attrib == _A_NORMAL)
{
cout << "  普通文件  ";
}
else if (file.attrib == _A_RDONLY)
{
cout << "  只读文件  ";
}
else if (file.attrib == _A_HIDDEN)
{
cout << "  隐藏文件  ";
}
else if (file.attrib == _A_SYSTEM)
{
cout << "  系统文件  ";
}
else if (file.attrib == _A_SUBDIR)
{
cout << "  子目录  ";
}
else
{
cout << "  存档文件  ";
}
cout << endl;
} while (_findnext(longf, &file) == 0);//int __cdecl _findnext(long, struct _finddata_t *);如果找到下个文件的名字成功的话就返回0,否则返回-1
_findclose(longf);
}




【剖析】对于_find一类的方法我还是第一次遇见(没见识...),但是这个方法真的特别有用,不仅可以对文件夹目录下的所有子文件夹进行寻找、遍历,并且还可以进行文件格式的遍历,对于读取训练或测试数据,直接后缀名写上“*.jpg”或者"*.png"等就可以把该文件夹下的所有图片都图进去了,这样就避免了图片名称无规律而读入困难的问题。

struct _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];
};


time_create,time_access,time_write分别指创建时间,最近访问时间,和最后修改时间。name为文件(或文件夹)名称。attrib描述的文件的系统属性,它由多个attributes组合而成,在MSDN中描述如下:
_A_ARCH Archive. Set whenever the file is changed, and cleared by the BACKUP command. Value: 0x20
_A_HIDDEN Hidden file. Not normally seen with the DIR command, unless the /AH option is used. Returns information about normal files as well as files with this attribute. Value: 0x02
_A_NORMAL Normal. File can be read or written to without restriction. Value: 0x00
_A_RDONLY Read-only. File cannot be opened for writing, and a file with the same name cannot be created. Value: 0x01
_A_SUBDIR Subdirectory. Value: 0x10
_A_SYSTEM System file. Not normally seen with the DIR command, unless the /AS option is used. Value: 0x04
_A_SUBDIR属性表示该对象是一个子目录,我们可以探测这个位是否被设置来判断这是一个文件还是文件夹。这样,我们就可以采用递归的办法,来获取每个子目录下的文件信息。

实例:



参考博文:

/content/4155020.html
/article/9960464.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: