在遍历目录之前,先了解下windows的一个结构体:
struct _finddata_t 是用来存储文件各种信息的结构体,定义如下(ps:使用此结构体的时候需要添加#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];
};
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 |
首先第一个函数_findfirst的原型:
long _findfirst( char *filespec, struct _finddata_t *fileinfo );
查找成功的话,将返回一个long型的唯一的查找用的句柄(就是一个唯一编号)。这个句柄将在_findnext函数中被使用。若失败,则返回-1。
参数:filespec:标明文件的字符串,可支持通配符。比如:*.c,则表示当前文件夹下的所有后缀为C的文件。fileinfo :这里就是用来存放文件信息的结构体的指针。这个结构体必须在调用此函数前声明,不过不用初始化,只要分配了内存空间就可以了。函数成功后,函数会把找到的文件的信息放入这个结构体中。
第二个函数的原型:
int _findnext( long handle, struct _finddata_t *fileinfo );
成功返回0,否则返回-1。
参数:handle:即由_findfirst函数返回回来的句柄。fileinfo:文件信息结构体的指针。找到文件后,函数将该文件信息放入此结构体中。
第三个函数的原型:
int _findclose( long handle );
成功返回0,失败返回-1。
参数:handle :_findfirst函数返回回来的句柄。
接下来查看遍历C盘根目录下的内容程序就简单了。:
#include <direct.h>
#include <stdio.h>
#include <io.h>
#include <string.h>
int main(int argc, char* argv[])
{
char path[100] = "C:/";
struct _finddata_t fa;
long handle;
if((handle = _findfirst(strcat(path,"*"),&fa)) == -1L)
{
printf("The Path %s is wrong!\n",path);
return 0;
}
printf("the content of this path is:\n");
do
{
if( (fa.attrib == _A_ARCH||_A_HIDDEN||_A_RDONLY||_A_SUBDIR||_A_SYSTEM) && ~strcmp(fa.name,".")&& ~strcmp(fa.name,".."))
printf("%s\n",fa.name);
}while(_findnext(handle,&fa) == 0); /* 成功找到时返回0*/
printf("\n");
_findclose(handle);
return 0;
}