Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file from a folder to another folder

Tags:

c++

linux

file-io

How do I copy a file from one folder to another folder using C++?

like image 831
user1165435 Avatar asked Feb 03 '12 07:02

user1165435


3 Answers

This should be the minimal code required:

#include <fstream>

// copy in binary mode
bool copyFile(const char *SRC, const char* DEST)
{
    std::ifstream src(SRC, std::ios::binary);
    std::ofstream dest(DEST, std::ios::binary);
    dest << src.rdbuf();
    return src && dest;
}

int main(int argc, char *argv[])
{
    return copyFile(argv[1], argv[2]) ? 0 : 1;
}

it glosses around some potentially complicated issues: error handling, filename character encodings... but could give you a start.

like image 152
CapelliC Avatar answered Nov 20 '22 01:11

CapelliC


With std::filesystem::copy_file from C++17:

#include <exception>
#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main()
{
    fs::path sourceFile = "path/to/sourceFile.ext";
    fs::path targetParent = "path/to/target";
    auto target = targetParent / sourceFile.filename(); // sourceFile.filename() returns "sourceFile.ext".

    try // If you want to avoid exception handling, then use the error code overload of the following functions.
    {
        fs::create_directories(targetParent); // Recursively create target directory if not existing.
        fs::copy_file(sourceFile, target, fs::copy_options::overwrite_existing);
    }
    catch (std::exception& e) // Not using fs::filesystem_error since std::bad_alloc can throw too.  
    {
        std::cout << e.what();
    }
}

I've used std::filesystem::path::filename to retrieve the source filename without having to type it manually. However, with std::filesystem::copy you can omit passing the filename to the target path at all:

fs::copy(sourceFile, targetParent, fs::copy_options::overwrite_existing);

Change the behaviour of both functions with std::filesystem::copy_options.

like image 24
Roi Danton Avatar answered Nov 20 '22 00:11

Roi Danton


If you're willing to use the Boost C++ libraries, take a look at filesystem::copy_file().

Here's a previous question covering copy_file():

How to use copy_file in boost::filesystem?

like image 43
jjlin Avatar answered Nov 20 '22 01:11

jjlin