我是 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/