• 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);

  • 相关阅读:
    centos 安装Phpstorm
    PostgreSQL 里面的 BIGSERIAL
    如何下载symfony
    换行
    javaScript 真经 小感 this 指向
    css3 抖动
    jq 抖动效果
    还是 js 替代 vw vh 了
    常用 Math 属性及方法
    js 判断浏览器类型及版本
  • 原文地址:https://www.cnblogs.com/eaglegeek/p/4558023.html
Copyright © 2020-2023  润新知