linux下使用C++遍历一个目录

一、程序代码

编译环境:RedHat下的g++

#include<stdio.h>
#include<unistd.h>
#include<dirent.h>   //format of directory entries
#include<string.h>
#include<sys/stat.h>
#include<stdlib.h>

void printdir(char* dir, int depth)
{
    DIR *dp; //DIR: a type representing a directory stream
    struct dirent *entry;
    //dirent: dirent.h
    //structure dirent shall include the following members:
    //  ino_t      d_ino        |File serial number
    //  char       d_name[]     |Name of entry
    struct stat statbuf;
    //stat: sys/stat.h
    //structure stat contains the following fields:
    //  dev_t      st_dev       |ID of device containing file
    //  ino_t      st_ino       |inode number
    //  mode_t     st_mode      |protection
    //  nlink_t    st_nlink     |number of hard links
    //  uid_t      st_uid       |user ID of owner
    //  gid_t      st_gid       |group ID of owner
    //  dev_t      st_rdev      |device ID (if special file)
    //  off_t      st_size      |total size, in bytes
    //  blksize_t  st_blksize   |blocksize for file system I/O
    //  blkcnt_t   st_blocks    |number of 512B blocks allocated
    //  time_t     st_atime     |time of last access
    //  time_t     st_mtime     |time of last modification
    //  time_t     st_ctime     |time of last status change
    
    //opendir: dirent.h
    //DIR *opendir(const char *name);
    //0.The opendir() function opens a directory stream corresponding to the 
    //  directory [name], and returns a pointer to the directory stream. The
    //  stream is positioned at the first entry in the directory.
    if((dp = opendir(dir)) == NULL)
    {
        fprintf(stderr, "cannot open directory: %s\n", dir);
        return;
    }

    chdir(dir);
    //chdir: unistd.h
    //int chdir(const char *path);
    //0.chdir() changes the current working directory of the calling process 
    //  to the directory specified in [path].

    //readdir: dirent.h
    //struct dirent *readdir(DIR *dirp);
    //0.The readdir() function returns a pointer to a [dirent] structure 
    //  representing the next directory entry in the directory stream pointed 
    //  to by [dirp]. It returns NULL on reaching the end of the directory
    //  stream or if an error occured.
    //1.The data returned by readdir() may be overwritten by subsequent calls
    //  to readdir() for the same directory stream.
    while((entry = readdir(dp)) != NULL)
    {
        lstat(entry -> d_name, &statbuf);
        //stat, fstat, lstat: unistd.h
        //int stat(const char *path. struct stat *buf);
        //int fstat(int fd, struct stat *buf);
        //int lstat(const char *path, struct stat *buf);
        //0.These functions returns information about a file. No permissions are 
        //  required on the file itself, but - in the case of stat() and lstat()
        //  - execute (search) permission is required on all of the directories
        //  in [path] that lead to the file.
        //1.stat() stats the file pointed to by [path] and fills in [buf].
        //2.lstat() is identical to stat(), except that if [path] is a symbolic 
        //  link, then the link itself is stat-ed, not the file that is refers to.
        //3.fstat() is identical to stat(), except that the file to be stat-ed is
        //  specified by the file descriptor [fd].
        //4.On success, zero is returned. On error, -1 is returned.

        //sys/stat.h macros
        //S_ISBLK(m): Test for a block special file
        //S_ISCHR(m): Test for a character special file
        //S_ISDIR(m): Test for a directory
        //S_ISFIFO(m): Test for a pipe or FIFO special file
        //S_ISREG(m): Test for a regular file
        //S_ISLNK(m): Test for a symbolic link
        //S_ISSOCK(m): Test for a socket
        if(S_ISDIR(statbuf.st_mode))
        {
            /*找到文件夹,但忽略.和..*/
            if(strcmp(".", entry -> d_name) == 0 ||
                strcmp("..", entry -> d_name) == 0)
            {
                continue;
            }

            printf("%d|%*sDir:%s/\n", depth, depth, " ", entry -> d_name);

            //递归打印
            printdir(entry -> d_name, depth + 4);
        }
        else
        {
            printf("%d|%*sFile:%s\n", depth, depth, " ", entry -> d_name);
        }
    }

    chdir("..");
    
    closedir(dp);
    //closedir: dirent.h
    //int colsedir(DIR *dirp)
    //0.The closedir() function closes the directory stream associated with [dirp].
    //  A successful call to closedir() also closes the underlying file descriptor
    //  associated with [dirp]. The directory stream descriptor dirp is not 
    //  available after this call.
    //1.The closedir() function returns 0 on success. On error, -1 is returned.
}

int main(int argc, char* argv[])
{
    char *topdir = ".";
    if(argc >= 2)
    {
        topdir = argv[1];
    }

    printf("Directory scan of %s:\n", topdir);    
    printdir(topdir, 0);
    //printdir("/home/", 0);
    //printdir("/home/oracle/Documents/", 0);
    printf("done.\n");
    exit(0);
}

二、运行结果

173046_Bf1P_1425762.png

END

转载于:https://my.oschina.net/Tsybius2014/blog/313026

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值