• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: changing file name when copying a file in the same directory
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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: Mike Abdullah <email@hidden>
  • Date: Fri, 10 Jun 2011 21:23:11 -0700

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

References: 
 >changing file name when copying a file in the same directory (From: Sandeep <email@hidden>)
 >Re: changing file name when copying a file in the same directory (From: Jerry Krinock <email@hidden>)
 >Re: changing file name when copying a file in the same directory (From: Jens Alfke <email@hidden>)

  • Prev by Date: Re: ObjC stdin equivalent? and other questions
  • Next by Date: Printing graphics plus text
  • Previous by thread: Re: changing file name when copying a file in the same directory
  • Next by thread: NSFileHandle and Data Integrity
  • Index(es):
    • Date
    • Thread