Re: Distinguish between Directory and File
Re: Distinguish between Directory and File
- Subject: Re: Distinguish between Directory and File
- From: glenn andreas <email@hidden>
- Date: Wed, 3 Oct 2007 16:07:05 -0500
On Oct 3, 2007, at 4:00 PM, Dani wrote:
isDirectory is always set to YES even if it's a file and not a
directory. I don't know why. Here's the code:
- (NSArray *)listFilesInFolder:(NSString *)apath
{
NSArray *filesList;
NSMutableArray *onlyFiles;
NSString *path;
BOOL isDir;
int i;
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager]
enumeratorAtPath:apath];
filesList = [direnum allObjects];
[self llistarArray:filesList];
for (i=0;i<[filesList count];i++)
{
path = [filesList objectAtIndex:i];
[[NSFileManager defaultManager] fileExistsAtPath:path
isDirectory:&isDir];
if (isDir==false)
{
[onlyFiles addObject:[filesList objectAtIndex:i]];
}
}
return filesList;
}
In theory in the onlyFiles NSMutableArray should be only files.
The problem is that enumeratorAtPath returns an enumerator that is a
"rooted" in the given path. Asking for all objects (which, if you
have an enumerator already and are then going to iterate over it is
wasteful - you should just use the enumerator iteration methods btw)
will return relative paths. Asking "existsAtPath" is actually going
to return "NO" since that expects full paths - and as a result, isDir
is never changed from the garbage value it had to start with (which
happened to be 0).
So instead, something like this:
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager]
enumeratorAtPath:apath];
NSString *subpath;
while ((subpath = [direnum nextObject]) != nil) {
NSString *fullPath = [apath stringByAppendingPathComponent: subpath];
if ([[NSFileManager defaultManager] fileExistsAtPath: fullPath
isDirectory: &isDir] == YES && isDir == YES) {
[onlyFiles addObject: fullPath]; // or subpath if you only want
relative sub-paths
}
}
Glenn Andreas email@hidden
<http://www.gandreas.com/> wicked fun!
quadrium2 | build, mutate, evolve, animate | images, textures,
fractals, art
_______________________________________________
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