[1]文件夹名 [2]后缀格式 [3]保存文件名的文件
dataTxt txt flieName.txt
实现同一文件夹下同类文件类型文件名字的获取,并将文件名字保存在txt文件中,BUT 出现了一个问题,该文件夹内的文件必须全部为同一类型
///[1]文件夹名 [2]后缀格式 [3]保存文件名的文件
///dataTxt txt flieName.txt
///实现同一文件夹下同类文件类型文件名字的获取,并将文件名字保存在txt文件中,BUT 出现了一个问题,该文件夹内的文件必须全部为同一类型
#include <io.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
void getAllFiles(string filePath, vector<string>& saveFileName, string postfix)
{
struct _finddata_t fileInfo;
long handle = 0;
string pathAndFileName;
if ((handle = _findfirst(pathAndFileName.assign(filePath).append("\\*").c_str(), &fileInfo)) != -1)
{
do
{
if ((fileInfo.attrib & _A_SUBDIR)) // is folder?
{
if (strcmp(fileInfo.name, ".") != 0 && strcmp(fileInfo.name, "..") != 0) ///目的是为了去掉第一行 dataTxt/..
{
getAllFiles(pathAndFileName.assign(filePath).append("/").append(fileInfo.name), saveFileName, postfix);
///saveFileName.push_back(pathAndFileName.assign(filePath).append("/").append(fileInfo.name));
//获取文件夹全部文件,不分后缀
}
}
else
{
string fileStr = fileInfo.name;
string prepostfix = "." + postfix;
int index = fileStr.find(prepostfix); ///在fileStr中查找子串prepostfix
///如果查找成功则输出查找到的第一个位置,否则返回-1;
string postStr = fileStr.substr(index, fileStr.size()); ///主要功能是复制子字符串,要求从指定位置开始,并具有指定的长度
if (0 == postStr.compare(prepostfix))
{
saveFileName.push_back(pathAndFileName.assign(filePath).append("/").append(fileInfo.name));
}
}
} while (_findnext(handle, &fileInfo) == 0);
_findclose(handle);
}
}
int main(int argc,char** argv)
{
string basedir = argv[1]; ///基本目录
string postfix = argv[2]; ///后缀名||文件扩展名(filename extension)
vector<string> files;
getAllFiles(basedir, files, postfix);
string savingName = argv[3];
ofstream fout(savingName);
//fout << files.size() << endl;
for (size_t i = 0; i < files.size(); i++)
{
fout << files[i] << endl;
}
fout.close();
std::cerr << "成功读取 " << files.size() << " 个文件" << std::endl;
system("pause");
return 0;
}