天天看點

Unix C學習之檔案夾操作

  1. 檔案夾的内容:檔案夾的内容就是檔案夾裡的檔案或檔案夾
  2. 檔案夾的權限:r讀 w寫 x可通過
  3. DIR *opendir(const char *name);

    #include <sys/types.h>

    #include <dirent.h>

    功能:打開一個檔案夾

    參數: name 指定要打開的檔案夾的名字

    傳回值:錯誤 NULL errno被設定 成功 傳回一個指向檔案夾流的指針

  4. int closedir(DIR *dirp);

    #include <sys/types.h>

    #include <dirent.h>

    功能:關閉檔案夾流

    參數: dirp 指定檔案夾流 也就是要關閉的檔案夾流

    傳回值:成功 0 錯誤 -1 errno被設定

  5. struct dirent * readdir(DIR *dirp);

    #include <dirent.h>

    功能:從檔案夾流中讀取一條資訊

    參數: dirp 指定了檔案夾流

    傳回值: NULL 到達檔案夾的末尾或者錯誤發生 如果是錯誤發生 errno被設定

    結構體說明

    struct dirent {
           ino_t          d_ino;       /* inode number */
           off_t          d_off;       /* not an offset; see NOTES */
           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]; /* filename */
    };
               
    #ifndef     __T_STDIO_H__
    #define     __T_STDIO_H__
    
    #include <stdio.h>
    #define E_MSG(STR,VAL)  do{\
                                perror(STR);\
                                return (VAL);\
                            }while(0)
    #endif
               
    #include <t_stdio.h>
    #include <sys/types.h>
    #include <dirent.h>
    #include <errno.h>
    
    int main(int argc, char *argv[]){
    
        //打開檔案夾
        DIR *dir = opendir(argv[1]);
        if(!dir) E_MSG("opendir", -1);
        printf("opendir success... \n");
    
        //從檔案夾流中讀取一條資訊
        struct dirent *item = NULL;
        while((item=readdir(dir))){
            printf("filename:%s\tinode:%lu\n", item->d_name, item->d_ino);
        }   
    
        //關閉檔案夾流
        closedir(dir);
        return 0;
    }
               

繼續閱讀