• 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: How to check if file exists?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to check if file exists?


  • Subject: Re: How to check if file exists?
  • From: Fritz Anderson <email@hidden>
  • Date: Sat, 10 May 2014 14:19:17 -0500

On May 10, 2014, at 2:06 PM, William Squires <email@hidden> 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 (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: 
 >How to check if file exists? (From: William Squires <email@hidden>)

  • Prev by Date: How to check if file exists?
  • Next by Date: Re: How to check if file exists?
  • Previous by thread: How to check if file exists?
  • Next by thread: Re: How to check if file exists?
  • Index(es):
    • Date
    • Thread