Warm tip: This article is reproduced from stackoverflow.com, please click
c++ file-copying windows

CopyFile cant found the file while i can open it from fopen

发布于 2020-03-27 10:18:28

I try to create a program that creates a backup of a folder. The problem is that when I try to use CopyFile function I get error 2 (FILE_NOT_FOUND) but I can open the file using the fopen and the exact same path. I also use utf-8 format.


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());
        }
    }

}

From this code, I should expect to copy the file but I get the FILE_NOT_FOUND. does anybody know why this is happening? (if you need any other part of the code let me know)

Questioner
Nikos Issaris
Viewed
118
Nikos Issaris 2019-07-03 21:38

Thanks for the help at the comments, the solution was to use std::filesystem::copy_file(i,destinationpath); instead of
CopyFile(floc , (LPCTSTR)destinationpath.c_str(), false); Use of wstring wasnt necessary. So the code now is like that:

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;
        }
    }
}