Linux-C-Day2

目錄操作

  • opendir
  • readdir
  • closedir
  • DIR *
  • stuct dirent
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>

int main(void){
    DIR *dfd;


//    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 */
//        char           d_name[256]; /* filename */
//    };
/**
 *  file type:
#define DT_UNKNOWN       0
#define DT_FIFO          1
#define DT_CHR           2
#define DT_DIR           4
#define DT_BLK           6
#define DT_REG           8  -- 常規文件
#define DT_LNK          10
#define DT_SOCK         12
#define DT_WHT          14
 */
    struct dirent *dp;

    if ((dfd = opendir(".")) == NULL){
        perror("opendir:");
        exit(1);
    }

    while ((dp = readdir(dfd)) != NULL){
        switch (dp->d_type) {
            case DT_DIR:
                printf("dir :  %s\n", dp->d_name);
                break;
            case DT_REG:
                printf("file :  %s\n", dp->d_name);
                break;
            default:
                printf("other %d :  %s\n", dp->d_type, dp->d_name);
                break;
        }
    }
    closedir(dfd);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章