码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 读取文件夹下文件名

时间:2018-03-14 20:44:53      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:find   name   rcm   ios   push   mes   close   out   struct   

在C++ 中读取文件夹下的文件名,如果存在子文件夹,递归读取子文件下的文件名

 1 #include <fstream>
 2 #include <iostream>
 3 #include <string>
 4 #include <sstream>
 5 #include <vector>
 6 #include <io.h>
 7 
 8 using namespace std;
 9 void getAllFiles(string path, vector<string>& files, string postfix)
10 {
11     // file handle 
12     long   hFile = 0;
13     // file info. struct
14     struct _finddata_t fileinfo;
15     string pathp;
16     if ((hFile = _findfirst(pathp.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
17     {
18         do
19         {
20             if ((fileinfo.attrib &  _A_SUBDIR))  // is folder?
21             {
22                 // is folder
23                 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
24                 {
25                     //files.push_back(p.assign(path).append("/").append(fileinfo.name));//saving folder name
26                     getAllFiles(pathp.assign(path).append("/").append(fileinfo.name), files, postfix);//find postfix file recursively
27                 }
28             }
29             else    //not folder
30             {
31                 string filestr = fileinfo.name;
32                 string prepostfix = "." + postfix;
33                 int idx = filestr.find(prepostfix);
34                 string poststr = filestr.substr(idx, filestr.size());
35                 if (0 == poststr.compare(prepostfix))
36                     files.push_back(pathp.assign(path).append("/").append(fileinfo.name));
37 
38             }
39         } while (_findnext(hFile, &fileinfo) == 0);  //find next
40         _findclose(hFile);
41     }
42 }
43 //测试
44 void main()
45 {
46     string basedir = "D:/video/t/";
47     string savingname = "filename.txt";
48 
49     string postfix = "hik"; // specify postfix
50     vector<string> files;
51 
52     getAllFiles(basedir, files, postfix);
53 
54     int filenum = files.size();
55 
56     // saving as txt file
57     ofstream outfilestream(savingname);  // output file stream        
58     outfilestream << filenum << endl;
59     for (int i = 0; i < filenum; i++)
60     {
61         outfilestream << files[i] << endl;
62     }
63     outfilestream.close();
64 }

 

C++ 读取文件夹下文件名

标签:find   name   rcm   ios   push   mes   close   out   struct   

原文地址:https://www.cnblogs.com/Keven-Lee/p/8569726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!