打开目录
—opendir函数
DIR *opendir(const char *name);
name—目录名
成功返回 目录流stream,失败返回 NULL 并设置 errno
读目录
—readdir函数struct dirent *readdir(DIR *dirp);
dirp—目录流stream(opendir目录成功的返回值)
struct dirent {
ino_t d_ino; /* Inode number */
off_t d_off; /* Not an offset; see below */
unsigned short d_reclen; /* Length of this record */
unsigned char d_type; /* Type of file; not supported by all filesystem types*/
char d_name[256]; /* Null-terminated filename */
};成功返回dirent结构体,如果读到目录流末尾返回 NULL 失败返回 NULL 并设置 errno
关闭目录
—closedir函数int closedir(DIR *dirp);
dirp—目录流stream(opendir目录成功的返回值)
成功返回 0,失败返回 -1并设置 errno
创建目录
—mkdir函数
int mkdir(const char *pathname, mode_t mode);
pathname—创建的目录名
mode—目录权限
成功返回 0,失败返回 -1并设置 errno
删除空目录
—rmdir函数
int rmdir(const char *pathname);
pathname—目录名
成功返回 0,失败返回 -1并设置 errno
修改当前进程工作目录
—chdir函数
int chdir(const char *path);
path—将要改变的目录名
成功返回 0,失败返回 -1 并设置 errno
获取当前进程工作目录
—getcwd函数
char *getcwd(char *buf, size_t size);
buf—获取到的目录名
size—当前buf的大小—sizeof(buf)
成功返回 指向当前目录的字符串,失败返回 NULL 并设置 errno
递归遍历目录DEMO
使用目录函数递归遍历目录,将指定目录下所有的文件以及子目录下的文件遍历出来。
#include <stdio.h> //standard c library
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
struct dirent *dirs; //directions information
int jubFile(const char *pathname); /* Determine whether it is a directory or a file */
int recurReadDir(const char *dirname,int (*func)(const char *))
{
DIR * dirp;
char path[256] = {'\0'};
dirp = opendir(dirname);//open directions
if(dirp == NULL){
perror("opendr error"); //open directions failed
return -1;
}
while((dirs = readdir(dirp)) != NULL){
if(strcmp(dirs->d_name,".") == 0 || strcmp(dirs->d_name,"..") == 0)
continue;
sprintf(path,"%s/%s",dirname,dirs->d_name);
(*func)(path);
}
closedir(dirp); //close current directions
return 0;
}
/*
*Determine whether it is a directory or a file
*/
int jubFile(const char *pathname)
{
int rest;
struct stat infor;
rest = stat(pathname,&infor); //get file information
if(rest == -1){
perror("stat error"); //get file information failed
return -1;
}
if((infor.st_mode & S_IFMT) == S_IFDIR){
recurReadDir(pathname,jubFile); //
}else{
printf("%-10s\n",dirs->d_name); //if pathname is not a directions then printf file
}
return 0;
}
int main(int argc,char **argv)
{
if(argc == 1){
jubFile("."); //if no parameter are entered,the current path is specified!ei
}else
while(--argc > 0)
jubFile(*++argv); //parameter dispose
return 0;
}