相关函数是
opendir -> readdir -> closedir
可以分别通过man opendir , man readdir ,man closedir 在linux下面去查询函数用法等.
seekdir,telldir,scandir
linux shell 遍历目录同样经常使用。
一次opendir -> readdir ,只能遍历当前目录的子目录,不会递归遍历。
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *dirname);
#include <dirent.h>
struct dirent *readdir(DIR *dirp);
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
当然dirend的结构可以在man readdir中找到
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; not supported
by all file system types */
char d_name[256]; /* filename */
};
所以根据这些可以得到代码如下,运行格式为 ./xx <path> //path 为目录路径
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#define MAX_LEN 512
static char* fullpath;
static int dopath();
int main(int argc,char* argv[]){
printf("--------------------------------------------------\n");
fullpath=(char *)malloc(MAX_LEN);
strcpy(fullpath,argv[1]);
printf("fullpath is %s\n",fullpath);
dopath();
int ret;
return 0;
}
static int dopath(){
struct stat statbuf;
DIR *dir;
struct dirent *dirp;
if(lstat(fullpath,&statbuf)<0){
//if get statbuf failed
printf("maybe the fullpath error !!");
return -1;
}
//has got statbuf
printf("S_ISDIR(statbuf.st_mode) is %d\n",S_ISDIR(statbuf.st_mode));
//when S_ISDIR()==1 it is a dir when ==0 maybe it is a file
if(S_ISDIR(statbuf.st_mode)==0){
printf("it is not a dir ,maybe it's a file !!");
return 0;
}
dir = opendir(fullpath);
if( dir ==NULL){
printf("can not read dir\n");
return 0;
}
dirp = readdir(dir);
while(dirp){
dirp = readdir(dir);
printf("inode: %d d_reclen: %d name: %s\n",dirp->d_ino,dirp-
>d_reclen,dirp->d_name);
}
closedir(dir);
return 0;
}