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

在windows 、linux下读取目录下所有文件名

2015-08-07 19:24 579 查看
Windows要引入的头文件是<Windows.h>

主要是两个函数FindFirstFile、FindNextFile

MSDN里是这么说的:

FindFirstFile function

Searches a directory for a file or subdirectory with a name that matches a specific name (or partial name if wildcards are used).

这个函数是用来在给定目录下搜索某个文件用的(比如指定一个特定的文件名,看它是不是在那个目录),如果要实现枚举所有文件名,就要用通配符来匹配文件名:比如最常用的

‘*’就表示匹配所有文件名(也包括了'.'和'..')

FindNextFile function

Continues a file search from a previous call to the FindFirstFile, FindFirstFileEx, or FindFirstFileTransacted functions.

这个是紧接着上一个函数调用来查找剩下的满足条件的文件名的。

这两个函数配合起来,就能用于枚举指定目录下的所有文件名:

vector<string> getFileNames(const string& inputDir, const string& filter=“*”) {
vector<string> result;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
hFind = FindFirstFile((inputDir + filter).c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind){
perror("FindFirstFile Error\n");
exit(-1);
}
do {
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
result.push_back(ffd.cFileName);
}
} while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
return result;
}


  通过指定filter参数,这个函数还有匹配特定名字的文件的能力,比如我要搜索目录下所有的.lib文件,可以这么写getFileNames(inputDir, "*.lib");

还有一点要注意的是,搜索的时候inputDir是和filter连起来组成一个路径的,所以inputDir结尾要加上"\\":比如"C:\\User\\somebody\\"

在linux下要引入的头文件是<dirent.h>

主要的两个函数是:

DIR *opendir(const char *pathname);

struct dirent *readdir(DIR *dp);

这两个函数的设计就更像我们读取一个文件时的做法了,先打开,然后每次读的时候,返回一个目录项(可能是子目录,也可能是文件)

vector<string> getFileNames(const string& inputDir){
vector<string> result;
auto hFind = opendir(inputDir.c_str());
struct dirent* ffd;
ffd = readdir(hFind);
while(ffd != NULL){
if(ffd->d_type != DT_DIR){
result.push_back(ffd->d_name);
}
ffd = readdir(hFind);
}
return result;
}


可以发现,这个api就没有了在windows 下,过滤文件名的能力,所以在指定路径的时候也可以不加最后的“//”(加上也不会错!)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: