温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c++ - CopyFile cant found the file while i can open it from fopen
c++ file-copying windows

c++ - 当我可以从fopen打开文件时,CopyFile找不到文件

发布于 2020-03-27 10:37:27

我尝试创建一个创建文件夹备份的程序。问题是,当我尝试使用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。有人知道为什么会这样吗?(如果您需要代码的其他任何部分,请告诉我)

查看更多

查看更多

提问者
Nikos Issaris
被浏览
268
Nikos Issaris 2019-07-03 21:38

感谢您在评论中提供的帮助,解决方案是使用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;
        }
    }
}