如何在Windows中使用C ++复制和粘贴文件?

我GOOGLE了这个,但我仍然对如何使用它感到困惑。 我正在做一个文件pipe理器,我想能够复制和粘贴一个文件到一个新的目录。 我知道要复制我需要使用file.copy() ,但我不知道如何实现它到我的代码。

我想用fstream来做这个。

如果您正在使用Win32 API,则考虑查看函数CopyFileCopyFileEx

您可以使用类似于以下方法的第一个:

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

这会将在szFilePath的内容中找到的文件复制到szFilePath的内容中,如果复制不成功,将会返回FALSE 。 要详细了解为什么函数失败,可以使用GetLastError()函数,然后在Microsoft文档中查找错误代码。

 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)); } 

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

我不知道你的意思是拷贝和粘贴一个文件; 这是没有意义的。 你可以复制一个文件到另一个位置,我想这就是你问的。

这里是我的实现复制文件,你应该看看boost文件系统,因为该库将成为标准c ++库的一部分。

 #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的答案看起来不错,但是解决方案很慢。

在本机C ++中,您可以使用:

System :: IO :: File :: Copy(“Old Path”,“New Path”);