linux下获取所有文件夹和文件,支持nfs和xfs(C++实现)

http://www.oschina.net/code/snippet_203297_9027

.要获取一个指定目录下的文件或文件夹,在linux下一般用dirent来做。dirent结构体中d_type表示类型,4表示目录,8表示普通文件,0表示未知设备。一般的文件系统直接用d_type判断,不会出现问题。由于项目中用到了nfs,实际的文件存放在另一台机器上,通过nfs映射到当年机器上。读文件的时候发现d_type为0,导致判断错误。因此用stat中的st_mode来判断是否为文件或文件夹。

File.h

//written by baoer1024 on 2012-3-22
#ifndef _FILE_H_
#define _FILE_H_

#include <vector>
#include <string>
#include <time.h>
#include <sys/stat.h>
using namespace std;

const int MAX_DUR = 5*60;  //时间阈值

class File
{
public:
    //获取路径下的所有文件夹
	vector<string> GetFolders(const string &path);
	
	//获取路径下的所有文件,可指定文件后缀名
	vector<string> GetFiles(const string &path, const string &postfix="");
	
	//检查文件或目录是否准备好,一定程度上防止数据正在拷贝的时候去读写。
	//方法是检查文件或目录的access time是否在5分钟以前
	bool IsPrepared(const string &path);
	
	//判断是否为文件夹
	bool IsFolder(const string &path);
	
	//判断是否为文件
	bool IsFile(const string &path);
};

#endif

File.cpp

//written by baoer1024 on 2012-3-22
#include "File.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

//获取路径下的所有文件夹
vector<string> File::GetFolders(const string &path)
{
   vector<string> folders;
   struct dirent* ent = NULL;
   DIR* pDir;
   pDir = opendir(path.c_str());
   while(NULL != (ent = readdir(pDir)))
   {
	  string fullpath = path + "/" + ent->d_name;
	  //if(4 == ent->d_type)  //在nfs或xfs下,有的目录d_type也是0
	  if(IsFolder(fullpath))
	  {
		 if(strcmp(ent->d_name, ".")!=0 && strcmp(ent->d_name, "..")!=0)
		 {
			folders.push_back(ent->d_name);
		 }
	  }
   }
   closedir(pDir);
   return folders;
}

//获取路径下的所有文件,可指定文件后缀名
vector<string> File::GetFiles(const string &path, const string &postfix)
{
   vector<string> files;
   struct dirent* ent = NULL;
   DIR* pDir;
   pDir = opendir(path.c_str());
   while(NULL != (ent = readdir(pDir)))
   {
	  string fullpath = path + "/" + ent->d_name;
	  //if(8 == ent->d_type)  //在nfs或xfs下,有的文件d_type也是0
	  if(IsFile(fullpath))
	  {
		 if(postfix == "" || strstr(ent->d_name, postfix.c_str())!=NULL)
		 {
			files.push_back(ent->d_name);
		 }
	  }
   }
   closedir(pDir);
   return files;
}

//检查文件或目录是否准备好,一定程度上防止数据正在拷贝的时候去读写。
//方法是检查文件或目录的access time是否在5分钟以前
bool File::IsPrepared(const string &path)
{
    struct stat st;
    stat(path.c_str(), &st);
    return time(0)-st.st_ctime >= MAX_DUR;
}

//判断是否为文件夹,用stat的标志来判断
bool File::IsFolder(const string &path)
{
   struct stat st; 
   int ret = stat(path.c_str(), &st);
   return ret>=0 && S_ISDIR(st.st_mode);
}

//判断是否为文件,用stat的标志来判断
bool File::IsFile(const string &path)
{
   struct stat st; 
   int ret = stat(path.c_str(), &st);
   return ret>=0 && S_ISREG(st.st_mode);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值