Я не могу сделать копию всех файлов в папке с C ++

Я хотел написать программу на C++, где она скопировала все файлы в папке и вставила их в другую папку. На данный момент я справился только с одним файлом.

#include <iostream>
#include <windows.h>

using namespace std;

int main (int argc, char *argv[])
{
    CopyFile ("C:\\Program Files (x86)\\WinRAR\\Rar.txt","C:\\Users\\mypc\\Desktop\\don't touch\\project\\prova", TRUE);

1 ответ

Как предполагает один из комментариев, CopyFile копирует только один файл за раз. Одним из вариантов является циклическое перемещение по каталогу и копирование файлов. Использование файловой системы (о которой можно прочитать здесь), позволяет нам рекурсивно открывать каталоги, копировать файлы этих каталогов и каталоги каталогов и так далее, пока все не будет скопировано. Кроме того, я не проверял аргументы, вводимые пользователем, поэтому не забывайте, что это важно для вас.

# include <string>
# include <filesystem> 

using namespace std;
namespace fs = std::experimental::filesystem;
//namespace fs = std::filesystem; // my version of vs does not support this so used experimental

void rmvPath(string &, string &);

int main(int argc, char **argv)
{
    /* verify input here*/

    string startingDir = argv[1]; // argv[1] is from dir
    string endDir = argv[2]; // argv[2] is to dir

    // create dir if doesn't exist
    fs::path dir = endDir;
    fs::create_directory(dir);

    // loop through directory
    for (auto& p : fs::recursive_directory_iterator(startingDir))
    {
        // convert path to string
        fs::path path = p.path();
        string pathString = path.string();

        // remove starting dir from path
        rmvPath(startingDir, pathString);

        // copy file
        fs::path newPath = endDir + pathString;
        fs::path oldPath = startingDir + pathString;


        try {
            // create file
            fs::copy_file(oldPath, newPath, fs::copy_options::overwrite_existing);
        }
        catch (fs::filesystem_error& e) {
            // create dir
            fs::create_directory(newPath);
        }
    }

    return 0;
}


void rmvPath(string &startingPath, string &fullPath) 
{
    // look for starting path in the fullpath
    int index = fullPath.find(startingPath);

    if (index != string::npos)
    {
        fullPath = fullPath.erase(0, startingPath.length());
    }
}
Другие вопросы по тегам