標籤:path include pen char 設定 off fse 相關資訊 div
檔案夾相關函數介紹
//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*指標指向下一條記錄項。
//rewinddir
#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 512void 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;}
linux檔案夾操作及遞迴遍曆檔案夾