【问题标题】:I can not make a copy of all the files inside a folder with C ++我无法使用 C++ 复制文件夹中的所有文件
【发布时间】:2019-06-27 03:51:27
【问题描述】:

我想用 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() 只复制一个文件。要复制多个文件,您需要遍历所有文件,并为每个文件调用CopyFile()。查找函数FindFirstFile()FindNextFile() 以获取实现该循环的选项,如果您需要复制文件属性(例如保护),请查找GetFileAttributes()SetFileAttributes()。请记住,目录包含目录 - 要复制目录,有必要循环遍历目录中的所有文件 - 递归。
  • 或者,例如SHFileOperation(),则不需要循环,可以使用通配符。
  • 查看std::filesystem::copy,它应该适用于任何系统,而不仅仅是 Windows。

标签: c++ windows directory dev-c++ file-copying


【解决方案1】:

正如其中一位 cmets 所建议的,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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多