c++ - 在 C++ 中查找和移动文件

标签 c++

我是 C++ 的新手我刚读过 <C++ Primer> 4ed .现在我想实现一个小程序来帮助我管理一些 mp3我电脑里的文件。

我有一个 .txt文件,其中包括我要移动(而不是复制)到新文件夹(在同一列中)的文件的所有名称(实际上是部分名称)。例如 .txt 中的“word”和“file”我想移动所有 .mp3文件名包含“word”或“file”的文件到新文件夹。希望我的描述清楚,Opps..

我知道如何读取 .txt 中的字符串进入 set<string>并遍历它,但我不知道如何在文件夹中搜索和移动文件。我只是想知道我还应该学习什么才能实现这个功能。我读了C++ Primer但我仍然无能为力,这真的很难过......

最佳答案

要在 C++ 中移动文件,您不必使用外部库,如 Boost.Filesystem ,但您可以使用标准功能。

有新的filesystem API ,它有一个 rename功能:

#include <iostream>
#include <filesystem>

int main() {
  try {
    std::filesystem::rename("from.txt", "to.txt");
  } catch (std::filesystem::filesystem_error& e) {
    std::cout << e.what() << '\n';
  }
  return 0;
}

缺点是编译它,你需要一个最新的C++17编译器。 (我在 gcc 8.0.1 上测试过,我还需要链接 -lstdc++fs)。

但是今天应该在任何 C++ 编译器上工作的是旧的 C API,它还提供了 rename (cstdio) :

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cerrno>

int main() {
  if(std::rename("from.txt", "to.txt") < 0) {
    std::cout << strerror(errno) << '\n';
  }
  return 0;
}

但请注意,在这两种情况下,如果源文件和目标文件不在同一文件系统上,重命名将失败。然后你会看到这样的错误:

filesystem error: cannot rename: Invalid cross-device link [from.txt] [/tmp/to.txt]

在这种情况下,您只能制作一个拷贝,然后删除原始文件:

#include <fstream>
#include <iostream>
#include <ios>
#include <cstdio>

int main() {
  std::ifstream in("from.txt", std::ios::in | std::ios::binary);
  std::ofstream out("to.txt", std::ios::out | std::ios::binary);
  out << in.rdbuf();
  std::remove("from.txt");
}

或者使用新的 API:

#include <iostream>
#include <filesystem>

int main()
{
  try {
    std::filesystem::copy("from.txt", "to.txt");
    std::filesystem::remove("from.txt");
  } catch (std::filesystem::filesystem_error& e) {
    std::cout << e.what() << '\n';
  }
  return 0;
}

关于c++ - 在 C++ 中查找和移动文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22201663/

相关文章:

c++ - Qt Progressbar 增加超过它应该的

c# - 有哪些 VC# 无法做到而 VC++(原生)可以做到的事情?

c++ - C++中单一类型和单一元素的通用容器

c++ - C++中void函数的重复计时

c++ - 如何在 if 条件中声明一个变量?

c++ - 是否从任何被视为未定义行为的整数中减去 INT_MIN?

c++ - 从基类模板列表中实例化子类对象

c++ - 按值传递参数的复制省略

c# - 在 Windows 上更改任务栏按钮颜色

c++ - 如何检查用户输入?