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