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

  • Follow-Ups:
    • Re: changing file name when copying a file in the same directory
      • From: Mike Abdullah <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>)

  • Prev by Date: NSFileHandle and Data Integrity
  • Next by Date: Re: NSFileHandle and Data Integrity
  • Previous by thread: Re: changing file name when copying a file in the same directory
  • Next by thread: Re: changing file name when copying a file in the same directory
  • Index(es):
    • Date
    • Thread