【发布时间】:2019-11-14 02:13:08
【问题描述】:
我尝试创建一个创建文件夹备份的程序。问题是当我尝试使用 CopyFile 函数时出现错误 2 (FILE_NOT_FOUND) 但我可以使用 fopen 和完全相同的路径打开文件。我也使用 utf-8 格式。
void Folder::copy_files(std::string destination) {
bool error = false;
std::string destinationpath = destination;
for (std::string i : Get_files_paths()) {
std::string destinationpath = destination;
destinationpath.append(split_file_folder_name(i));
#ifdef DEBUG
char str[100];
const char* floc_cstr = i.c_str();
LPCTSTR floc = (LPCTSTR)floc_cstr;
printf("\t[DEBUG]FILE_LOC_PATH: %s\n", floc_cstr);
std::cout << "\t[DEBUG]memory loc" << floc << std::endl;
#pragma warning(disable : 4996)
FILE* fp = fopen(floc_cstr, "r");
if (fp == NULL) {
printf("file not found");
exit(1);
}
else {
printf("file found \n");
fscanf(fp, "%s", str);
printf("%s", str);
}
fclose(fp);
print_last_error(GetLastError());
#endif
error = CopyFile(floc , (LPCTSTR)destinationpath.c_str(), false);
if (error == false) {
print_last_error(GetLastError());
}
}
}
从这段代码中,我应该希望复制文件,但我得到了 FILE_NOT_FOUND。 有人知道为什么会这样吗? (如果您需要代码的任何其他部分,请告诉我)
【问题讨论】:
-
检查目的路径是否存在。 CopyFile 不会创建文件夹或子文件夹。
-
目标路径存在。此外,如果目标路径不存在,则错误编号为 3 (PATH_NOT_FOUND)
-
您可以使用资源管理器查看文件吗?
-
从
const char*到LPCTSTR的转换让我怀疑你的LPCTSTR真的是const wchar_t*。尝试使用它,看看会发生什么:CopyFileA(floc_cstr, destinationpath.c_str(), false); -
@NikosIssaris 啊...好吧,那么您应该在您的项目中改用
std::wstrings。另外,请查看带有std::filesystem::path参数的std::filesystem::file_copy,这些参数应该与L"paths"和普通"paths"一起使用。
标签: c++ windows file-copying