将文件重命名为已存在的文件名

Renaming a file to name of file that already exists

本文关键字:存在 文件名 命名为 文件 重命名      更新时间:2023-10-16

例如,我正在重命名文件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 到原始文件名...我一直这样做...我一定在使用您用来做的所有代码时缺少一些东西