文件夹相关函数介绍
//mkdir 函数创建文件夹
//readdir 读文件夹
//mkdir 函数创建文件夹
#include <sys/stat.h> #include <sys/types.h> int mkdir(const char *pathname, mode_t mode);
//rmdir 删除文件夹
#include <unistd.h> int rmdir(const char *pathname);
//dopendir/fdopendir //打开文件夹
DIR是一个结构体,是一个内部结构,用来存储读取文件夹的相关信息。
DIR *opendir(const char *name); DIR *fdopendir(int fd);
//readdir 读文件夹
#include <dirent.h> struct dirent *readdir(DIR *dirp); 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 supportedby all file system types */ char d_name[256]; /* filename */ };
readdir 每次返回一条记录项。。DIR*指针指向下一条记录项。
#include <sys/types.h> #include <dirent.h> void rewinddir(DIR *dirp);
把文件夹指针恢复到文件夹的起始位置。
//telldir函数
#include <dirent.h> long telldir(DIR *dirp);
函数返回值是为文件夹流的当前位置,表示文件夹文件距开头的偏移量。
//seekdir
#include <dirent.h> void seekdir(DIR *dirp, long offset);seekdir表示设置文件流指针位置。
//closedir 关闭文件夹流
#include <sys/types.h> #include <dirent.h> int closedir(DIR *dirp);
使用递归来遍历文件夹下的文件
#include<stdio.h> #include <errno.h> #include<stdlib.h> #include<string.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #define MAX_PATH 512 void print_file_info(char *pathname); void dir_order(char *pathname); void dir_order(char *pathname) { DIR *dfd; char name[MAX_PATH]; struct dirent *dp; if ((dfd = opendir(pathname)) == NULL) { printf("dir_order: can't open %s %s", pathname,strerror(errno)); return; } while ((dp = readdir(dfd)) != NULL) { if (strncmp(dp->d_name, ".", 1) == 0) continue; /* 跳过当前文件夹和上一层文件夹以及隐藏文件*/ if (strlen(pathname) + strlen(dp->d_name) + 2 > sizeof(name)) { printf("dir_order: name %s %s too long ", pathname, dp->d_name); } else { memset(name, 0, sizeof(name)); sprintf(name, "%s/%s", pathname, dp->d_name); print_file_info(name); } } closedir(dfd); } void print_file_info(char *pathname) { struct stat filestat; if (stat(pathname, &filestat) == -1) { printf("cannot access the file %s", pathname); return; } if ((filestat.st_mode & S_IFMT) == S_IFDIR) { dir_order(pathname); } printf("%s %8ld ", pathname, filestat.st_size); } int main(int argc, char *argv[]) { if (argc == 1) { dir_order("."); } else { dir_order(argv[1]); } return 0; }