user2761933
user2761933

Reputation: 179

Why isn't my rename file working?

I am having trouble with renaming a file. I'm attempting to delete several lines of an existing file, and replace it with the new one.

string line;   
ifstream myfile(filename);  
ofstream outfile;  
outfile.open(filename.append(".new"));  

if(myfile.is_open()) {
    //loop here that runs through code and calles
    //outfile << line; repeatedly
}

int test = rename(filename.append(".new").c_str(),filename.c_str());
if (test == 0) cout << "Success";
else cout << "Failure";

From what I have seen online, I would expect this to create the new document, fill it, and then replace the original with the updated one.

Does anyone see where I have gone wrong?

Upvotes: 2

Views: 4974

Answers (1)

David Heffernan
David Heffernan

Reputation: 613461

It looks like it is failing because you still have both files opened. You most likely cannot rename the file while it is locked. Close the file before attempting to rename it.

In addition, you'll need to delete the original file before you can rename.

In pseudo code this is what you need to do:

  • Open original file.
  • Open temporary .new file.
  • Perform whatever task you do.
  • Close both files.
  • Delete original file.
  • Rename.

It's likely that your C++ implementation will set errno when a call to rename fails. You should therefore check the value of errno to find out why the call fails. Do familiarise yourself with error reporting mechanisms so that you can diagnose problems yourself.

Upvotes: 4

Related Questions