利用readdir函数,读取目录信息

在 Linux 系统下,权限设置很详细,不想 windows 的文件系统,文件可以随时访问。

在 Linux 中,只要对目录具有读权限,就可以获得目录信息。获取目录信息,主要分为3步:

  1. opendir 函数打开目录;
  2. readdir 函数读取目录信息;
  3. closedir 关闭已打开目录。

我们先看一下他们的函数原型:

1、opendir

#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
DIR *fdopendir(int fd);

2、readdir

#include <dirent.h>
struct dirent *readdir(DIR *dirp);
int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result);

3、closedir

#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
  1. opendir 用来打开参数 name指定的目录,并返回 DIR * 形态的目录流,类似于文件操作中的文件描述符;
  2. readdir 用来从参数 dir 从所指向的目录中读取出目录信息,返回一个struct dirent 结构的指针;
  3. closedir 用来关闭参数 dir 指向的目录。

在读取目录时,readdir 会将读出的数据存在与 struct dirent 结构一致的指针。下面来看看 struct dirent 的定义。

struct dirent
{
     long d_ino;
     off_t_off;
     unsigned short d_reclen;
     char d_name [NAME_MAX+1];
}

则我们通过这三个函数,就可以获取一个目录下面的文件信息。简单的程序如下:

#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int my_readir(const char * path)
{
	DIR		* dir;
	struct dirent	* ptr;
	if ((dir = opendir(path)) == NULL) {
		perror("opendir");
		return -1;
	}
	while ((ptr = readdir(dir))!=NULL) {
		printf("file name: %sn",ptr->d_name);
	}
	closedir(dir);
	return 0;
}
int main(int argc, char ** argv)
{
	if (argc < 2) {
		printf("listfile <target path>n");
		exit(1);
	}
	if (my_readir(argv[1]) < 0) {
		exit(1);
	}
	return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>