简体   繁体   中英

I can not make a copy of all the files inside a folder with C ++

I wanted to write a program in C++ where it copied all the files in a folder and pasted them into another folder. For now, I managed only with a single file.

#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);

As one of the comments suggest, CopyFile only copies one file at a time. One option is to loop through the directory and copy the files. Using filesystem (which can be read about here ), allows us to recursively open directories, copy that directories files and the directories directories and on and on until everything has been copied. Also, I did not check the arguments being input by the user, so don't forget that if its important to you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM