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

  • 相关阅读:
    JSON
    什么是Jsonp?
    用border做三角形
    前端模块化
    Web 前端
    前端性能优化
    Ajax的原理
    node.js基础语法
    【真·新手初篇】菜鸟们都戳进来看看(欢迎大神指导)
    2019.11.20 开启一天的工作
  • 原文地址:https://www.cnblogs.com/jediael/p/4304233.html
Copyright © 2011-2022 走看看