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

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 FindFirstFileFindFirstFileEx, or FindFirstFileTransacted functions.

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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 下,过滤文件名的能力,所以在指定路径的时候也可以不加最后的“//”(加上也不会错!)。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值