标签:目录操作
目录相关函数介绍#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);
#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\n %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\n", 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\n", pathname, filestat.st_size); } int main(int argc, char *argv[]) { if (argc == 1) { dir_order("."); } else { dir_order(argv[1]); } return 0; }
版权声明:欢迎转载,如有不足之处,恳请斧正。
标签:目录操作
原文地址:http://blog.csdn.net/huangshanchun/article/details/47132851