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

时间:2013-07-29 16:51:39

标签: c++ windows file fstream

我用谷歌搜索了这个,但我仍然对如何使用它感到困惑。我正在制作文件管理器,我希望能够将文件复制并粘贴到新目录中。我知道要复制我需要使用file.copy(),但我不确定如何在我的代码中实现它。

我想用fstream做到这一点。

6 个答案:

答案 0 :(得分:7)

如果您使用的是Win32 API,请考虑查看函数CopyFileCopyFileEx

您可以使用类似于以下内容的方式使用第一个:

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

这会将szFilePath内容中找到的文件复制到szCopyPath的内容,如果副本不成功,则会返回FALSE。要了解有关函数失败原因的更多信息,可以使用GetLastError()函数,然后在Microsoft文档中查找错误代码。

答案 1 :(得分:4)

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

答案 2 :(得分:1)

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

我不知道复制和粘贴文件是什么意思;这是没有意义的。您可以将文件复制到另一个位置,我认为这就是您所要求的。

答案 3 :(得分:1)

这是我复制文件的实现,你应该看看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的答案看起来不错,但解决方案很慢。

答案 4 :(得分:0)

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

答案 5 :(得分:-3)

System :: IO :: File :: Copy(&#34; Old Path&#34;,&#34; New Path&#34;);

相关问题