您的位置:首页 > 运维架构 > Linux

linux c遍历文件夹 和文件查找的方法

2015-01-09 16:47 357 查看
linux c遍历文件夹的方法比较简单,使用c来实现

#include <iostream>
#include <stdio.h>

#include <sys/types.h>
#include <dirent.h>
#include <sys/dir.h>
#include <sys/stat.h>

...

enum
{
DT_UNKNOWN = 0,     //未知类型
DT_FIFO = 1,        //管道
DT_CHR = 2,         //字符设备文件
DT_DIR = 4,         //目录
DT_BLK = 6,         //块设备文件
DT_REG = 8,         //普通文件
DT_LNK = 10,        //连接文件
DT_SOCK = 12,       //套接字类型
DT_WHT = 14         //
};

void loopDir(const char *dir_path) {
  char temp[256] = {0};
  struct dirent *pdirent;

DIR *d_info =  opendir(dir_path);
if (d_info)
{
while ((pdirent = readdir(d_info)) != NULL)
{
if (pdirent->d_type & DT_REG)
{
//普通文件
}
if (pdirent->d_type & DT_DIR)
{
//目录,递归

}
}

}
}

...


在类Unix或linux (OSX,iOS,Android系统)下面搜索某一类型的文件可以用OgreSearchOps来使用,非常方便,对应 win32 则需要另外一套机制

// 头文件引用部分
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include <io.h>
#else
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>

#include "OgreSearchOps.h"
#endif

void MfindFiles(const std::string &dir_path,const std::string &partten,std::vector<std::string> &arr)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
_finddata_t FileInfo;
string strfind = dir_path + "\\" + partten;
long Handle = _findfirst(strfind.c_str(), &FileInfo);

if (Handle == -1L)
{
exit(-1);
}
do{
if (FileInfo.attrib & _A_SUBDIR)
{
}
else
{
string filename = (dir_path + "\\" + FileInfo.name);
arr.push_back(FileInfo.name);
}
}while (_findnext(Handle, &FileInfo) == 0);

_findclose(Handle);
#else
findFiles(dir_path, partten, false, false, &arr);
#endif
}

// 测试  搜索所有的.plist 后缀名文件
std::vector<std::string> plist_file_list;
MfindFiles(effect_path, "*.plist",plist_file_list);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: