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

来源:互联网 发布:计算机科学python编程 编辑:程序博客网 时间:2024/05/22 05:10

获取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属性表示该对象是一个子目录,我们可以探测这个位是否被设置来判断这是一个文件还是文件夹。这样,我们就可以采用递归的办法,来获取每个子目录下的文件信息。

实例:




参考博文:

http://www.cnblogs.com/Binhua-Liu/archive/2010/06/06/1752627.html

http://blog.csdn.net/gengoo/article/details/4622084





1 0