Reputation: 179
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
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:
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