日期:2014-05-16  浏览次数:20674 次

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