简体   繁体   中英

Renaming a file to name of file that already exists

i am renaming file for example file1.txt to "newFile.txt" but when the code runs for the next time. the file newFile.txt already exists so the newly file created whos name is "file1.txt" doesn't renamed to "newFile.txt"
what i want is if the "newFile.txt" already exists renaming "file1.txt" should overwrite the "file1.txt" is it possible ??

Here goes my code

#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;
}

Your code works and renames a file only once.

The second time you run your program, file banana.txt already exist in that directory and function std::rename("afile.dat" , "banana.txt"); returns an error code.

So you need to check if a file with the new filename is already exists or handle an error after function std::rename .

One possible solution is to use the <filesystem> library - you can check it with std::filesystem::exists() from the <filesystem> header and copy the contents of the old file to the new file with copy option update_existing . Then you can remove the old file, effectively doing what you're looking to do. It'd look like so:

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 );
} else {
  std::filesystem::rename( oldFile, newFile );
}
outFile.open(newFile);

There ARE other ways to do this, but I find this to be a very easy approach in my subjective opinion (if performance of file close/open is acceptable for your case).

why not output contents of new file to another file, then delete the original file already there and ren the new file to original name

cat newfile > newfile1 del original file ren newfile1 to original file name ... i do this all the time ... i must be missing something using all that code you are using to do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM