zoukankan      html  css  js  c++  java
  • Linux系统常用目录操作函数

    参考《Linux程序设计》第二版P103

    扫描目录:


    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #include <dirent.h>
    #include <unistd.h>
    #include <sys/stat.h>
    
    void printdir(char *dir, int depth);
    
    int main(void){
    
        printf("Directory scan of /home:\n");
    
        printdir("/home", 0);
    
        printf("Done.\n");
    
        exit(0);
    
    }
    
    void printdir(char *dir, int depth){
    
        DIR *dp;
        struct dirent *entry;
        struct stat statbuf;
    
        if((dp = opendir(dir)) == NULL){
            fprintf(stderr, "Can not open directory: %s.\n", dir);
            return;
        }
        chdir(dir);
    
        while((entry = readdir(dp)) != NULL){
            lstat(entry->d_name, &statbuf);
            if(S_ISDIR(statbuf.st_mode)){
                if((strcmp(".", entry->d_name)==0)||(strcmp("..", entry->d_name) == 0)){
                     continue;
                }
                printf("%*s%s/\n", depth, "", entry->d_name);
                printdir(entry->d_name, depth+4);
            }
            else{
                printf("%*s%s\n", depth, "", entry->d_name);
            }
        }
        chdir("..");
        closedir(dp);
    
    }

    涉及的几个目录操作函数为:

    (1) DIR *opendir(const char *name);

    (2) struct dirent *readdir(DIR *dirp);

    (3) int closedir(DIR *dirp);

    (4) int chdir(const char *path);

    以及文件操作函数:
     int lstat(const char *path, struct stat *buf);

  • 相关阅读:
    Mybatis传入list的注意点
    synchronized锁
    手撸红黑树
    Vue cdn加速配置
    多线程之BlockingQueue中 take、offer、put、add的一些比较
    线程池
    ThreadLocal
    jdk LocalDateTime mybatis 空指针解决办法
    不同对象中 类型与属性名的属性 进行数据转换
    HashMap 的put方法
  • 原文地址:https://www.cnblogs.com/eaglegeek/p/4558023.html
Copyright © 2011-2022 走看看