On 10 Jun 2011, at 14:28, Jens Alfke wrote:

> 
> 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

I've built a nice helper for this: 
http://www.mikeabdullah.net/incrementing-paths.html_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to