我不能让所有的文件的副本用C文件夹内++

问题描述 投票:-1回答:1

我想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);
c++ windows directory dev-c++ file-copying
1个回答
0
投票

作为一个评论建议的时间,只的CopyFile拷贝一个文件。一种选择是通过目录循环,并复制文件。使用文件系统(它可以读到here),使我们能够递归开放目录,复制目录中的文件和目录的目录和进行,直到一切都已经被复制。另外,我没有检查参数是由用户输入,所以不要忘记,如果对你很重要。

# 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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.