27

I have an NSString containing a path, but it could be either a file, or a directory.

Is there an equivalent to the Python os.path.isdir() and os.path.isfile() methods in Cocoa?

2 Answers 2

48

See the NSFileManager Class Reference

[[NSFileManager defaultManager] fileExistsAtPath:pathname isDirectory:&directoryFlag]; 

For example:

NSString *file = @"/tmp/"; BOOL isDir = NO; if([[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir] && isDir){ NSLog(@"Is directory"); } 
Sign up to request clarification or add additional context in comments.

1 Comment

The important thing here is that the BOOL you pass into the isDirectory: portion of the method is the real BOOL to see if the file is a folder! The BOOL that is returned from the fileExistsAtPath:isDirectory: is just confirming if a file is a the path.
2

if the solution from htw doesn't work, try this:

NSString *file = @"/tmp/"; BOOL isDir NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:file]; while ((file = [dirEnum nextObject])) { [[NSFileManager defaultManager] fileExistsAtPath:file isDirectory:&isDir]; if(isDir){ NSLog(@"%@ is a directory", file); } } 

1 Comment

Your solution is actually same as how's but I'm afraid it contains a bug - the 'file' you get is a RELATIVE PATH (relative to the "/tmp") and not an absolute path, hence using 'fileExistsAtPath:isDirectory' on it - may fail. this method works on absolute paths.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.