【问题标题】:How can I copy and paste a file in Windows using C++?如何使用 C++ 在 Windows 中复制和粘贴文件?
【发布时间】:2013-07-29 13:52:24
【问题描述】:

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

我想用 fstream 来做这个。

【问题讨论】:

  • CopyFile 确实有效,但我如何使用 fstream 来做到这一点。
  • 那么您应该更改问题的标题并在问题中指定,而不是要求在 windows 中复制粘贴...

标签: c++ windows file fstream


【解决方案1】:

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

您可以通过类似于以下方式使用第一个:

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

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

【讨论】:

  • 我没有使用 WinAPI
  • 不,但您确实说过您正在“在 Windows”中工作,这意味着您可以访问 Win32 API。没有标准 C++ 包装器可以做与CopyFile/Ex() 相同的事情。如果您想要一个纯 C++ 解决方案,您必须创建并打开目标文件,然后手动循环通过源文件将字节复制到目标文件,如 Nisarg 和 dieram3 所示。不如使用原生操作系统解决方案高效。
  • 强烈建议调用 API 函数而不是自己滚动。
  • 这在 Windows 2008 R2 中不起作用,但在 2003 中起作用。为什么?
【解决方案2】:
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));
}

【讨论】:

  • 应该是istream_iterator<char>,或者更好的是istreambuf_iterator<char>ostream 也是如此。
【解决方案3】:

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

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

【讨论】:

  • 这就是我的意思。
【解决方案4】:

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

【讨论】:

    【解决方案5】:

    在原生 C++ 中,您可以使用:

    【讨论】:

      【解决方案6】:

      System::IO::File::Copy("旧路径", "新路径");

      【讨论】:

      • 阿里,你能把这个答案删掉吗?已经有几个现有的和更好的答案。如果您对其中任何一个有批评者,只需获得足够的评论声誉即可。至少,提供一些解释,包括一些 MSDN 文档等。就目前而言,这是一篇低质量的帖子。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多