zoukankan      html  css  js  c++  java
  • Linux系统常用目录操作函数 分类: B3_LINUX 20130218 16:44 486人阅读 评论(0) 收藏

    参考《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);

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    flask与Django的区别
    flask特殊装饰器
    flaskjinjia2模板
    flask类视图
    flask路由系统
    flask初识
    python2与python3 的安装与环境变量的添加
    WebGL_0007:强制横屏的参考
    NodeJS_0011:nodejs重定向到一个链接或本地的页面的方法
    NodeJS_0006:nodejs响应超时处理
  • 原文地址:https://www.cnblogs.com/lujinhong2/p/4637422.html
Copyright © 2011-2022 走看看