C++遍历文件夹

01//written by baoer1024 on 2012-3-22
02#ifndef _FILE_H_
03#define _FILE_H_
04 
05#include <vector>
06#include <string>
07#include <time.h>
08#include <sys/stat.h>
09using namespace std;
10 
11const int MAX_DUR = 5*60;  //时间阈值
12 
13class File
14{
15public:
16    //获取路径下的所有文件夹
17    vector<string> GetFolders(const string &path);
18     
19    //获取路径下的所有文件,可指定文件后缀名
20    vector<string> GetFiles(const string &path, const string &postfix="");
21     
22    //检查文件或目录是否准备好,一定程度上防止数据正在拷贝的时候去读写。
23    //方法是检查文件或目录的access time是否在5分钟以前
24    bool IsPrepared(const string &path);
25     
26    //判断是否为文件夹
27    bool IsFolder(const string &path);
28     
29    //判断是否为文件
30    bool IsFile(const string &path);
31};
32 
33#endif

2. [代码]File.cpp    跳至 [1] [2] [全屏预览]

01//written by baoer1024 on 2012-3-22
02#include "File.h"
03#include <string.h>
04#include <stdio.h>
05#include <stdlib.h>
06#include <dirent.h>
07 
08//获取路径下的所有文件夹
09vector<string> File::GetFolders(const string &path)
10{
11   vector<string> folders;
12   struct dirent* ent = NULL;
13   DIR* pDir;
14   pDir = opendir(path.c_str());
15   while(NULL != (ent = readdir(pDir)))
16   {
17      string fullpath = path + "/" + ent->d_name;
18      //if(4 == ent->d_type)  //在nfs或xfs下,有的目录d_type也是0
19      if(IsFolder(fullpath))
20      {
21         if(strcmp(ent->d_name, ".")!=0 && strcmp(ent->d_name, "..")!=0)
22         {
23            folders.push_back(ent->d_name);
24         }
25      }
26   }
27   closedir(pDir);
28   return folders;
29}
30 
31//获取路径下的所有文件,可指定文件后缀名
32vector<string> File::GetFiles(const string &path, const string &postfix)
33{
34   vector<string> files;
35   struct dirent* ent = NULL;
36   DIR* pDir;
37   pDir = opendir(path.c_str());
38   while(NULL != (ent = readdir(pDir)))
39   {
40      string fullpath = path + "/" + ent->d_name;
41      //if(8 == ent->d_type)  //在nfs或xfs下,有的文件d_type也是0
42      if(IsFile(fullpath))
43      {
44         if(postfix == "" || strstr(ent->d_name, postfix.c_str())!=NULL)
45         {
46            files.push_back(ent->d_name);
47         }
48      }
49   }
50   closedir(pDir);
51   return files;
52}
53 
54//检查文件或目录是否准备好,一定程度上防止数据正在拷贝的时候去读写。
55//方法是检查文件或目录的access time是否在5分钟以前
56bool File::IsPrepared(const string &path)
57{
58    struct stat st;
59    stat(path.c_str(), &st);
60    return time(0)-st.st_ctime >= MAX_DUR;
61}
62 
63//判断是否为文件夹,用stat的标志来判断
64bool File::IsFolder(const string &path)
65{
66   struct stat st;
67   int ret = stat(path.c_str(), &st);
68   return ret>=0 && S_ISDIR(st.st_mode);
69}
70 
71//判断是否为文件,用stat的标志来判断
72bool File::IsFile(const string &path)
73{
74   struct stat st;
75   int ret = stat(path.c_str(), &st);
76   return ret>=0 && S_ISREG(st.st_mode);
77}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值