2018年5月19日 星期六

search the specify files in all subdirectories

#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <time.h>

int dir_type(struct stat stat_buff) {
    // check file type from struct stat
    if (S_ISDIR(stat_buff.st_mode)) {
        return 1;
    }
    if (S_ISREG(stat_buff.st_mode)) {
        return 2;
    }
    return 0;        // consider as unknown file type
}
// dfs read directory, pathname can be positive/relative path
void dfs(char* pathname) {
    DIR* dir;
    struct dirent* dp;
    char next[1024];
    char *fname;
    if ((dir = opendir(pathname)) == NULL) {
        printf("%s: opendir error", pathname);
        return;
    }
    // read directory info
    while ((dp = readdir(dir)) != NULL) {
        sprintf(next, "%s/%s", pathname, dp->d_name);
        if (strcmp(dp->d_name, ".DS_Store") == 0 || strcmp(dp->d_name, "..") == 0 || strcmp(dp->d_name, ".") == 0) {
            // skip current folder, father folder
            continue;
        }
        struct stat stat_buff;
        if (stat(next, &stat_buff) < 0) {
            printf("%s: stat error", pathname);
            continue;
        }
        // read file type
        int ret_stat = dir_type(stat_buff);
        switch (ret_stat) {
            case 1:
                printf("Dir => %s\n", next);
                dfs(next);        // for directory read child node 
                break;
            case 2:
                fname=strstr(next, ".json");
                if (fname!=NULL)
                {
                    printf("Fpath = %s, len=%ld\n", next, strlen(next));
                    //printf("File => path = %s; uid = %d; size = %lld; create_time = %s", next, stat_buff.st_uid, stat_buff.st_size, ctime(&(stat_buff.st_mtime)));
                }
                break;
        }
    }
    closedir(dir);
}

int main(int argc, char** argv) {
    if (argc == 1) {
       printf("Usage: %s pathname\n", argv[0]);
        return;
    }
    dfs(argv[1]);
}

ref: Here-readdir

沒有留言:

張貼留言