linux檔案夾操作及遞迴遍曆檔案夾

來源:互聯網
上載者:User

標籤: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檔案夾操作及遞迴遍曆檔案夾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.