On May 10, 2014, at 2:06 PM, William Squires <wsqui...@satx.rr.com> wrote:

> If I have an NSString that contains a filename (and possibly a path, as typed 
> on the command-line), how can I check to see if the specified file actually 
> exists?

[ code fragment that collects a string representing a file name (not an 
absolute path) from argv[] ]

> How can I make sure MyFile.txt exists before trying to read it in?

1. See -[NSFileManager fileExistsAtPath:] or -fileExistsAtPath:isDirectory:. 
Careful practice would be to convert the partial path to an absolute one. Xcode 
handles working directories differently than the shell does.

2. Don’t do it. In the time between detecting the presence (or not) of the file 
and the time you attempt (or don’t) to read it, the file may have been deleted 
(or created). Preflighting file access works, until it doesn’t, when something 
happens that is nearly impossible to reproduce, or malware takes advantage of 
the gap.

Just attempt the read. If the file doesn’t exist then, you’ll be given an error 
or exception that will tell you so. Errors and exceptions are there to help 
you. It’s not much harder to write, and it works.

        — F


_______________________________________________

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

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

Reply via email to