Re: Creating a series of sequenced files
Re: Creating a series of sequenced files
- Subject: Re: Creating a series of sequenced files
- From: Jens Alfke <email@hidden>
- Date: Sat, 16 Apr 2016 18:41:12 -0700
> On Apr 16, 2016, at 2:56 PM, Alex Zavatone <email@hidden> wrote:
>
> The easy route is to use the file manager to see if the filename exists, then […] keep doing that until it finds a file that hasn’t yet been created and then write the file.
This is generally considered a bad approach, because it’s subject to race conditions: aanother process might create the file after you determine that it doesn’t exist yet, but before you open it. This will at the least cause unexpected failures, but at worst it can be (and has been) abused for security exploits — if a process running as root has this bug, it can be abused to gain root privileges.
The right way to do this is to try to open the file with the current filename, but using a mode that will fail if the file already exists. If it fails, you increment the filename and try again. In the Unix `open` system call you’d use mode O_CREAT | O_EXCL. You can also use `fopen` with mode “wx”, but the man page says this is not part of the C standard. I’m not sure how to do this using NSData, but it sounds as though NSDataWritingWithoutOverwriting would be the right flag to use.
> On Apr 16, 2016, at 2:36 PM, Carl Hoefs <email@hidden> wrote:
>
> I would hate to do this blindly, such as with fstat() in a loop, because there will potentially be many sequences, and each can grow to an arbitrary number. How do Finder and other OS X agents accomplish this?
You mean like how every time you duplicate a file in the Finder it appends “copy _n_” to the name? I’d be surprised if the Finder wasn’t doing this by just looping and retrying. You’d have to have an awfully long sequence of copies (thousands? Tens of thousands?) for this to start being noticeably slow.
If performance really is a problem, it’s probably best to enumerate the directory and find the highest existing filename with that pattern, then start your loop at the next filename.
—Jens
_______________________________________________
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