Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to move files and copy them from one disk to different without the usage of winapi?

It must be pure c++, I know about system("copy c:\\test.txt d:\\test.txt"); but I think it's the system function, not c++ solution, or I can mistakes?

like image 864
Marius Avatar asked Feb 22 '23 15:02

Marius


2 Answers

How about std::fstream? Open one for reading and another for writing, and use std::copy to let the standard library handle the copying.

Something like this:

void copy_file(const std::string &from, const std::string &to)
{
    std::ifstream is(from, ios::in | ios::binary);
    std::ofstream os(to, ios::out | ios::binary);

    std::copy(std::istream_iterator<char>(is), std::istream_iterator<char>(),
              std::ostream_iterator<char>(os));
}
like image 89
Some programmer dude Avatar answered Feb 24 '23 23:02

Some programmer dude


Try using copy_file from boost.

#include <boost/filesystem.hpp>

boost::filesystem::copy_file("c:\\test.txt","d:\\test.txt");

It will throw an exception if there is an error. See this page for more documentation: http://www.boost.org/doc/libs/1_48_0/libs/filesystem/v3/doc/reference.html#copy_file

like image 44
syvex Avatar answered Feb 24 '23 23:02

syvex