Re: changing file name when copying a file in the same directory
Re: changing file name when copying a file in the same directory
- Subject: Re: changing file name when copying a file in the same directory
- From: Jens Alfke <email@hidden>
- Date: Fri, 10 Jun 2011 14:28:12 -0700
On Jun 10, 2011, at 12:51 PM, Jerry Krinock wrote:
> do {
> newPath = [[[newPath stringByDeletingPathExtension]
> stringByAppendingString:suffix]
> stringByAppendingPathExtension:[self pathExtension]] ;
> } while ([[NSFileManager defaultManager] fileExistsAtPath:newPath]) ;
This will work most of the time, but it has a race condition: just because there was no file at that path when this method returns, is no guarantee that there’s still no such file when the caller attempts to create a file at the returned path. (This seems unlikely, but it can happen when two apps using the same code are trying to create a file at the same time. It’s also sometimes been exploited by malware to substitute a malicious file for the real one a system task thought it was creating.)
This race condition is pretty well known, and it’s generally considered wrong to test for existence prior to operating on a file. Instead, do the operation without checking and handle the error. (Sometimes called “ask for forgiveness, not permission”.)
So the correct code would look like:
do
compute a new filename to use on this iteration
try to copy to that filename
while the copy failed with a ‘duplicate filename’ error
—Jens
Attachment:
smime.p7s
Description: S/MIME cryptographic signature
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden