linux 访问目录及文件

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
#include <list>
 
using namespace std;
 
int main(int argc ,char **argv)
{
    typedef list<string> TStringList ;
    const int DIR_LENGTH = 1024 ;
    DIR *t_pDir = NULL;
    struct dirent *t_pDirent = NULL;
 
    TStringList t_olist ;
 
    char *pPath = "/mnt/share" ;
 
    if((t_pDir = opendir(pPath)) == NULL) //读取目录
    {
        perror("opendir \n ") ;
        return -1;
    }
 
 
    while((t_pDirent = readdir(t_pDir)) != NULL)
    {
        if ((strcmp((const char *)t_pDirent->d_name, ".") == 0) ||(strcmp((const char *)t_pDirent->d_name, "..") == 0))
        {
            continue;
        }
 
        char t_cNewDir[DIR_LENGTH] = {0};
        sprintf(t_cNewDir, "%s/%s", pPath, (char *)t_pDirent->d_name);
        struct stat t_mstat;
        memset(&t_mstat,0,sizeof(t_mstat));
        if(stat(t_cNewDir,&t_mstat) == -1)
        {
            perror("stat error \n") ;
            continue;
        }
        if(S_ISDIR(t_mstat.st_mode)) //判断是否是目录
        {
            DIR *t_pDirSecond = NULL;
            struct dirent *t_pDirentSecond = NULL;
            if((t_pDirSecond = opendir(t_pDirent->d_name)) == NULL) //读取目录
            {
                perror("second opendir \n ") ;
                return -1;
            }
 
            while((t_pDirentSecond = readdir(t_pDirSecond)) != NULL)
            {
                if ((strcmp((const char *)t_pDirentSecond->d_name, ".") == 0)
                        ||(strcmp((const char *)t_pDirentSecond->d_name, "..") == 0))
                {
                    //printf("second continue \n") ;
                    continue;
                }
 
                char t_cNewDirSecond[DIR_LENGTH] = {0};
                sprintf(t_cNewDirSecond, "%s/%s", t_cNewDir, (char *)t_pDirentSecond->d_name);
 
                memset(&t_mstat,0,sizeof(t_mstat));
                if(stat(t_cNewDirSecond,&t_mstat) == -1) 
                {
                    perror("stat error \n") ;
                    continue;
                }
                if(S_ISREG(t_mstat.st_mode))
                {
                    printf("file:%s is a regular file.\n",t_cNewDirSecond);
                    t_olist.push_back(t_cNewDirSecond) ;
                }
 
            }
            closedir(t_pDirSecond);
        }
 
 
    }
    printf("size = %d \n" , t_olist.size()) ;
    closedir(t_pDir);
    return 0;
}

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值