【问题标题】:CopyFile cant found the file while i can open it from fopenCopyFile 找不到该文件,而我可以从 fopen 打开它
【发布时间】: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


【解决方案1】:

感谢 cmets 的帮助,解决方案是使用std::filesystem::copy_file(i,destinationpath); 而不是
CopyFile(floc , (LPCTSTR)destinationpath.c_str(), false); 没有必要使用 wstring。所以现在的代码是这样的:

void Folder::copy_files(std::string destination) {
    const char* floc_cstr = NULL;
    bool error = false;
    std::string destinationpath;
    for (std::string i : Get_files_paths()) {
        try {
            destinationpath = destination;
            destinationpath.append(split_file_folder_name(i));
            error = fs::copy_file(i, destinationpath);
            if (error == false) {
                print_last_error(GetLastError());
            }
        }
        catch(std::exception e) {
#ifdef DEBUG
            std::cout << "[DEBUG]" << e.what() <<std::endl;
#endif
            std::cout << "file exist\n";
            continue;
        }
    }
}

【讨论】:

  • 效果很好。注意&lt;filesystem&gt; 有很多简洁的功能。我不确定您的代码中的 split_file_folder_name 做了什么,但它可能已经以一种或另一种方式存在于 std::filesystem::path
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
相关资源
最近更新 更多