将文件重命名为已存在的文件名
Renaming a file to name of file that already exists
例如,我正在重命名文件file1.txt
"newFile.txt"
但是当代码下次运行时。 该文件newFile.txt
已存在,因此新创建的名称为 "file1.txt"
的文件不会重命名为 "newFile.txt"
我想要的是,如果"newFile.txt"
已经存在重命名"file1.txt"
应该覆盖"file1.txt"
可以吗?
这是我的代码
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
char data[100];
fstream outfile;
outfile.open("afile.dat" , ios::out );
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
cout << "Reading from the file" << endl;
outfile >> data;
cout << data << endl;
outfile >> data;
cout << data << endl;
outfile.close();
// this is how i am renaming
std::rename("afile.dat" , "file2.txt");
return 0;
}
您的代码只能工作并重命名文件一次。
第二次运行程序时,文件banana.txt
已存在于该目录中,函数std::rename("afile.dat" , "banana.txt");
返回错误代码。
因此,您需要检查具有新文件名的文件是否已经存在或在函数std::rename
之后处理错误。
一种可能的解决方案是使用 <filesystem>
库 - 您可以使用 <filesystem>
标头中的std::filesystem::exists()
进行检查,并使用复制选项将旧文件的内容复制到新文件中 update_existing
.然后,您可以删除旧文件,有效地执行您要执行的操作。它看起来像这样:
if(outFile.is_open()) {
outFile.close();
}
if( std::filesystem::exists( newFile ) ) {
// this can be on the same line, just making a var for readability
auto copyOption{std::filesystem::copy_options::update_existing};
std::filesystem::copy_file( oldFile, newFile, copyOption);
std::filesystem::remove( oldFile );
// OR if you don't care what was in the old file anyways,
// ignore the previous three lines above and just remove it
std::remove(oldFile);
} else {
std::filesystem::rename( oldFile, newFile );
}
outFile.open(newFile);
还有其他方法可以做到这一点,但我发现在我的主观意见中这是一种非常简单的方法(如果文件关闭/打开的性能对您的情况是可以接受的(。
为什么不将新文件的内容输出到另一个文件,然后删除已经存在的原始文件并将新文件重新命名为原始名称
猫新文件> 新文件1德尔原始文件仁新文件1 到原始文件名...我一直这样做...我一定在使用您用来做的所有代码时缺少一些东西
相关文章:
- C++模板来检查友元函数的存在
- 从命令行c++发送文本文件名
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 既然存在危险,为什么项目要使用-I include开关
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- C++quit()函数中可能存在作用域问题
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- C++擦除(如果存在)
- g++ 说函数不存在,即使包含正确的标头
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- 由于相同的文件名/类名存在于不同的SO中而导致的SEG错误
- 将文件重命名为已存在的文件名
- gcovr-在xml覆盖Cobertura报告中是否存在损坏文件名的已知问题
- 异常处理 - 使用另一个文件名写入文件(如果该文件与原始文件名一起存在)
- 如果需要,如何从Qt中不存在的文件的文件名创建dir
- 检查文件夹中是否已经存在文件名
- 检查文件名中是否存在通配符
- 你如何检查一个特定的文件名是否存在于谷歌云存储?