How to copy and paste a file in Windows using C ++?

I searched for this in googled, but I'm still confused about how to use it. I am creating a file manager and want me to be able to copy and paste the file into a new directory. I know that for copying I need to use file.copy() , but I'm not sure how to implement it in my code.

I would like to do this with fstream.

+6
source share
6 answers

If you are using the Win32 API, consider CopyFile or CopyFileEx .

You can use the first one similar to the following:

 CopyFile( szFilePath.c_str(), szCopyPath.c_str(), FALSE ); 

This will copy the file found in the szFilePath contents to the szFilePath contents and return FALSE if the copy was unsuccessful. To learn more about why the function failed, you can use the GetLastError() function and then look for error codes in the Microsoft documentation.

+5
source
 void copyFile(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(is), std::istream_iterator(), std::ostream_iterator(os)); } 
+4
source

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx

I do not know what you mean by copy and paste the file; it's pointless. You can copy the file to another location, and I assume that you are asking.

+1
source

Here is my implementation for copying a file, you should take a look at the formatted file system, as this library will be part of the standard C ++ library.

 #include <fstream> #include <memory> //C++98 implementation, this function returns true if the copy was successful, false otherwise. bool copy_file(const char* From, const char* To, std::size_t MaxBufferSize = 1048576) { std::ifstream is(From, std::ios_base::binary); std::ofstream os(To, std::ios_base::binary); std::pair<char*,std::ptrdiff_t> buffer; buffer = std::get_temporary_buffer<char>(MaxBufferSize); //Note that exception() == 0 in both file streams, //so you will not have a memory leak in case of fail. while(is.good() and os) { is.read(buffer.first, buffer.second); os.write(buffer.first, is.gcount()); } std::return_temporary_buffer(buffer.first); if(os.fail()) return false; if(is.eof()) return true; return false; } #include <iostream> int main() { bool CopyResult = copy_file("test.in","test.out"); std::boolalpha(std::cout); std::cout << "Could it copy the file? " << CopyResult << '\n'; } 

Nisarg's answer looks good, but this solution is slow.

+1
source

In source C ++ you can use:

0
source

System :: IO :: File :: Copy ("Old path", "New path");

-3
source

Source: https://habr.com/ru/post/950559/


All Articles