判断当前路径是文件夹
1、ent->d_type & DT_DIR (注意在XFS文件系统下无效)
2、struct stat st; (各种文件系统下通用)
int ret = stat(path.c_str(), &st);
ret>=0 && S_ISDIR(st.st_mode)
判断当前路径是文件
1、ent->d_type & DT_REG
2、struct stat st; (各种文件系统下通用)
int ret = stat(path.c_str(), &st);
ret>=0 && S_ISREG(st.st_mode)
代码如下:
void listFile(const string& dirpath, vector<string> filenames)
{
DIR *pDir;
struct dirent *ent;
struct stat st;
pDir = opendir(dirpath .c_str());
while((ent = readdir(pDir)) != NULL)
{
if(strcmp(ent->d_name,".")==0 || strcmp(ent->d_name,"..")==0){
continue;
}
string dname;
dname.assign(ent->d_name);
string path = dirpath + "/" + dname;
int ret = stat(path.c_str(), &st);
if (ret>=0 && S_ISDIR(st.st_mode)) { //check is dir
listFile(path, filenames);
} else if(ret>=0 && S_ISREG(st.st_mode)) { //check is file
filenames.push_back(dname);
}
}
}