在VS2013中亲测有效,可以更改文件夹中的文件名(含子文件夹)。
同样,如果将main函数从第二部分改为第三部分,可以实现打印文件夹中所有文件名。
1、获取文件夹中所有文件名
#include <iostream>
#include <io.h>
#include <string>
#include <vector>
using namespace std;
void getFiles(const std::string & path, std::vector<std::string> & files)
{
//文件句柄
long hFile = 0;
//文件信息,_finddata_t需要io.h头文件
struct _finddata_t fileinfo;
std::string p;
if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
{
do
{
//如果是目录,迭代之;如果不是,加入列表。
if ((fileinfo.attrib & _A_SUBDIR))
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\\").append(fileinfo.name), files);
}
else
{
files.push_back(p.assign(path).append("\\").append(fileinfo.name));
}
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
2、更改文件夹中所有文件名
注意:源文件夹中所有文件将被删除,请注意保存!
int main()
{
//用来存储文件名
vector<std::string> filenames;
string path = "E:\\code\\num";
getFiles(path, filenames);
int i = 0;
for (auto file : filenames)
{
string str_name = to_string(i++);
string newPath = "E:\\code\\zrnum\\" + str_name + ".png";
rename(file.c_str(), newPath.c_str());
//cout << file << endl;
}
cout << "completed!" << endl;
system("pause");
return 0;
}
3、打印文件夹中所有文件名
int main()
{
//用来存储文件名
vector<std::string> filenames;
string path = "E:\\code\\num";
getFiles(path, filenames);
for (auto file : filenames)
{
cout << file << endl;
}
system("pause");
return 0;
}