Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a path within an NSString is to a directory, or a file?

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?

like image 818
dbr Avatar asked May 05 '09 17:05

dbr


2 Answers

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");
}
like image 129
hbw Avatar answered Oct 19 '22 03:10

hbw


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);
   }
}
like image 2
x4h1d Avatar answered Oct 19 '22 04:10

x4h1d