【问题标题】:CopyFile from one directory to another (C++)将文件从一个目录复制到另一个目录 (C++)
【发布时间】:2020-06-22 04:18:05
【问题描述】:

我在 Windows 上工作,我试图简单地将文件从一个目录移动到另一个目录。 我使用“CopyFile”方法,但复制的文件名有问题;我正在尝试这个:

#include <windows.h>
#include <stdio.h>

std::string source_path = "C:/ProgramData/RTD02/versions/versions.txt";
std::string destination_path = "C:/ProgramData/RTD02/principale.txt";
CopyFile(source_path.c_str(), destination_path.c_str(), 0);

事实上,文件“versions.txt”的内容被很好地复制到了“principale.txt”文件中。但我也想要将文件“principale.txt”的名称更改为“versions.txt”,我尝试了这个但它没有用:

 rename(destination_path.c_str(), source_path.c_str());

谢谢,

【问题讨论】:

  • 如果你的编译器支持 C++17 - 你可以使用它 - en.cppreference.com/w/cpp/filesystem/rename
  • 不幸的是它不支持,我使用的方法 rename() 来自
  • @JaziriRami:C++ 有重载;来自&lt;cstdio.h&gt;std::rename 可以与来自&lt;filesystem&gt; 的那个共存。

标签: c++ windows c++11 file-rename file-copying


【解决方案1】:

答案是你的目的地字符串必须是目的地。

std::string destination_path = "C:/ProgramData/RTD02/versions.txt";

如果您打算替换现有文件,请使用DeleteFileprincipale.txt 跟进成功的副本

【讨论】:

  • 谢谢@acraig5075!这是因为我在 rename() 方法中使用的路径;这是更正: rename("C:/ProgramData/RTD02/principale.txt","C:/ProgramData/RTD02/versions.txt");
【解决方案2】:

移动文件的 Windows 函数就是这样调用的,MoveFile。就像CopyFile 一样工作。

【讨论】:

  • 是的,你是对的,它们是来自 的函数
猜你喜欢
  • 2012-02-15
  • 2021-02-15
  • 2017-11-18
  • 2013-06-01
  • 2014-08-12
  • 2013-10-24
  • 2011-10-24
  • 1970-01-01
相关资源
最近更新 更多