目录操作与文件操作很类似,下面介绍一下目录操作函数。
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dirp);
struct dirent *readdir_r(DIR *dirp, struct dirent *entry);
void rewinddir(DIR *dirp); 把目录流的位置重新设定到开始之处。
int closedir(DIR *dirp);
函数的作用可以参照文件操作函数。这里把两个结构体的详细结构描述如下:
typedef struct {
int d_fd; /* file descriptor */
int d_loc; /* offset in block */
int d_size; /* amount of valid data */
char *d_buf; /* directory block */
} DIR; /* stream data from opendir() */
struct dirent {
ino_t d_ino; /* "inode number" of entry */
off_t d_off; /* offset of disk directory entry */
unsigned short d_reclen; /* length of this record */
char d_name[1]; /* name of file */
}
简单举例说明如下:;
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <dirent.h>
int main()
{
char text[8];
DIR *pdp = NULL;
struct dirent *sDirent = NULL;
if ((pdp = opendir(".")) != NULL) {
sDirent = readdir(pdp);
while (sDirent != NULL) {
if (strncmp(sDirent->d_name, "myfile", 6) == 0) {
printf("%s find/n",sDirent->d_name);
} else {
printf("%s/n",sDirent->d_name);
}
sDirent = readdir(pdp);
}
closedir(pdp);
}
return 0;
}