分类: LINUX
2009-10-09 21:48:04
LINUX下用C语言历遍目录 C语言列出目录2007-04-06 21:02功能: Linux下C语言目录历遍 (读取目录)
作者: 小徐
QQ: 339534039
转载请注明出处
呵呵,LINUX下历遍目录的方法一般是这样的
打开目录-》读取-》关闭目录
相关函数是
opendir -> readdir -> closedir
#include
DIR *opendir(const char *dirname);
#include
struct dirent *readdir(DIR *dirp);
#include
int closedir(DIR *dirp);
好了,三个函数都出来了呵呵,原型就是上面,给自己解释一下免得以后我自己忘了呵呵!我以经忘过好几回了,所以这次放上博客来
opendir用于打开目录,是类似于流的那种方式,返回一个指向DIR结构体的指针他的参数*dirname是一个字符数组或者字符串常量,
readdir函数用于读取目录,他只有一个参数,这个参数主opendir返回的结构体指针,或者叫句柄更容易理解些吧。这个函数也返回一个结构体指针 dirent *
dirent的结构如下定义
struct dirent
{
long d_ino; /* inode number */
off_t d_off; /* offset to this dirent */
unsigned short d_reclen; /* length of this d_name */
char d_name [NAME_MAX+1]; /* file name (null-terminated) */
}
结构体中d_ino存放的是该文件的结点数目,什么是结点数目呢我也说不清楚了呵呵,查一下其它资料了
d_off 是文件在目录中的编移,具体是什么意思我也不是很明白,我很少用到它,其本上就是用到d_name short d_reclen是这个文件的长度,需要注意的是这里的长度并不是指文件大小,因为大小和长度是2回事了,你可以用lseek将文件长度移得很长,但大小其实还是那么大.最后一个元素就是我们要的了,文件名称!
写了一个实例:
/**
* 功能: Linux下C语言目录历遍 (读取目录)
* 作者: 小徐
* 邮箱:
* QQ: 339534039
* 转载请注明出处
*/
#include
#include
#include
#include
#include
void print_usage(void);
void print_usage(void)
{
printf("Usage: test dirname\n");
}
int main(int argc,char *argv[])
{
DIR * dp;
struct dirent *filename;
if (argc < 2)
{
print_usage();
exit(1);
}
dp = opendir(argv[1]);
if (!dp)
{
fprintf(stderr,"open directory error\n");
return 0;
}
while (filename=readdir(dp))
{
printf("filename:%-10s\td_info:%ld\t d_reclen:%us\n",
filename->d_name,filename->d_ino,filename->d_reclen);
}
closedir(dp);
return 0;
}
将上面代码保存为readdir.c执行下面的命令进行编译测试
[root@phpos ~]# gcc readdir.c
[root@phpos ~]# ./a.out
Usage: test dirname
[root@phpos ~]# ./a.out /etc/samba/
filename:lmhosts d_info:49296 d_reclen:24s
filename:smb.conf d_info:49825 d_reclen:24s
filename:smbpasswd d_info:49402 d_reclen:24s
filename:.. d_info:47906 d_reclen:16s
filename:secrets.tdb d_info:49812 d_reclen:24s
filename:. d_info:49295 d_reclen:16s
filename:smbusers d_info:49377 d_reclen:24s
[root@phpos ~]# ./a.out /var/
filename:preserve d_info:31971 d_reclen:24s
filename:lock d_info:31966 d_reclen:16s
filename:yp d_info:31976 d_reclen:16s
filename:empty d_info:31962 d_reclen:24s
filename:run d_info:31972 d_reclen:16s
filename:lib d_info:31939 d_reclen:16s
filename:nis d_info:31969 d_reclen:16s
filename:local d_info:31965 d_reclen:24s
filename:spool d_info:31973 d_reclen:24s
filename:tmp d_info:31941 d_reclen:16s
filename:opt d_info:31970 d_reclen:16s
filename:log d_info:31959 d_reclen:16s
filename:crash d_info:31997 d_reclen:24s
filename:.. d_info:2 d_reclen:16s
filename:account d_info:32037 d_reclen:24s
filename:mail d_info:31968 d_reclen:16s
filename:cache d_info:31960 d_reclen:24s
filename:db d_info:31961 d_reclen:16s
filename:. d_info:31938 d_reclen:16s
[root@phpos ~]#