说明:C++访问文件夹中的内容没有python方便,这里做一下记录,提供实现数据从一个文件夹转移到另一个文件夹的接口。
应用场景:批量跑数据时,为了不在内部接口中输入当前数据的路径,避免层层传参数的麻烦,只在最里面的接口建一个临时文件夹,保存中间生成的文件,最后跳出最外层接口时,将临时文件夹里的内容全部复制到当前数据的路径下。
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
//将临时文件夹里的文件全部复制到相应数据的文件夹下面,并对临时文件夹进行清空处理,为下一套数据腾地方
void copy_file()
{
std::string strNamePath = "E://dst//"; // 目标文件夹
std::string source = "F://temp//";//临时文件夹
std::string inPath = source + '*';
intptr_t handle;
//long类型的数据范围是-2^31~2^31-1,但是__int64的数据范围是-2^63~ 2^63-1,这里使用intptr_t
struct _finddata_t fileinfo;
//第一次查找
handle = _findfirst(inPath.c_str(), &fileinfo);
if (handle == -1)
{
std::cout << "没有找到已保存的文件!!!" << std::endl;
return -1;
}
else
{
do
{
std::string filename = static_cast<std::string>(fileinfo.name);
std::string NamePath = source + filename;
std::string desNamePath = strNamePath + filename;
//files.push_back(NamePath);
//char* 转换成 LPCTSTR,CopyFile()函数参数必须是LPCTSTR类型
int num1 = MultiByteToWideChar(0, 0, NamePath.c_str(), -1, NULL, 0);
wchar_t* wide1 = new wchar_t[num1];
MultiByteToWideChar(0, 0, NamePath.c_str(), -1, wide1, num1);
int num2 = MultiByteToWideChar(0, 0, desNamePath.c_str(), -1, NULL, 0);
wchar_t* wide2 = new wchar_t[num2];
MultiByteToWideChar(0, 0, desNamePath.c_str(), -1, wide2, num2);
CopyFile(wide1, wide2, FALSE);//false代表覆盖,true不覆盖
remove(NamePath.c_str());//删除临时文件夹内容,为下一次测试腾位置
//找到的文件的文件名
//std::cout << fileinfo.name << std::endl;
//printf("%s\n", fileinfo.name);
} while (!_findnext(handle, &fileinfo));
_findclose(handle);
}
}