Linux下opendir()、readdir()和closedir()这三个函数主要用来遍历目录。在使用这三个函数前必须先包括以下两个头文件:
#include <sys/types.h>
#include <dirent.h>
opendir函数的原型为:
DIR *opendir(const char name);它返回一个DIR类型,是一个句柄,句柄要传给readdir()函数的参数就行了。(传入name路径,成功则返回非空DIR指针,否则返回NULL。)
readdir函数的原型为:struct dirent readdir(DIR dir);看它的参数就知道该参数是opendir函数返回的句柄,而该函数的返回值是struct dirent 类型:struct dirent {
ino_t d_ino; / inode number /
off_t d_off; / offset to the next dirent /
unsigned short d_reclen; / length of this record /
unsigned char d_type; / type of file /
char d_name[256]; / filename */
};
这个结构体的d_name存放的就是文件的名字,这里的文件包括普通文件,目录文件等等,在linux的思想中,所有的东西都是文件。
closedir函数的原型为:int closedir(DIR *dir);
**********************************************SearchDir.c****************************************************
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
char filename[256][256];
int len = 0;
int trave_dir(char* path, int depth)
{
DIR *d;
struct dirent *file;
struct stat sb;
if(!(d = opendir(path)))
{
printf("error opendir %s!!!/n",path);
return -1;
}
while((file = readdir(d)) != NULL)
{
if(strncmp(file->d_name, ".", 1) == 0)
continue;
strcpy(filename[len++], file->d_name);
if(stat(file->d_name, &sb) >= 0 && S_ISDIR(sb.st_mode) && depth <= 3)
{
trave_dir(file->d_name, depth + 1);
}
}
closedir(d);
return 0;
}
int main()
{
int depth = 1;
int i;
trave_dir("/usr/keygoe/ini/", depth);
for(i = 0; i < len; i++)
{
printf("%s/t", filename[i]);
}
printf("/n");
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)