繁体   English   中英

我无法使用 C++ 复制文件夹中的所有文件

[英]I can not make a copy of all the files inside a folder with 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);

正如评论之一所暗示的那样, 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());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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