views:

62

answers:

1

I am just learning Objective-C / Cocoa and I am a little unsure how I might extend my code to display the size of the files found.

EDIT 2

I have taken the comments from SMorgan & Peter below and worked them into the code ... comments most welcome.

// ------------------------------------------------------------------- **
// DISC: FILEWALKER ..... (cocoa_fileWalker.m)
// DATE: 28th September 2009
// DESC: List all "*.exr" files in specified directory
// ------------------------------------------------------------------- **

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *fileName;
    NSDictionary *attrDir;
    NSError *myError;
    NSNumber *fileSize;
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *rootPath = [@"~/Pictures" stringByExpandingTildeInPath];
    NSMutableArray *fileArray = [[NSMutableArray alloc] init];
    NSMutableString *newPath = [[NSMutableString alloc] init];

    NSLog(@"Home: %@",rootPath);

    for(fileName in [manager enumeratorAtPath:rootPath]){
     if ([[fileName pathExtension] isEqual:@"exr"]) {
      [fileArray addObject:fileName];

      [newPath setString:rootPath];
      [newPath appendString:@"/"];
      [newPath appendString:fileName];
      attrDir = [manager attributesOfItemAtPath:newPath error:&myError];
      fileSize = [attrDir objectForKey: @"NSFileSize"];
      NSLog(@"File: /%@ Size: %@", fileName, fileSize);
     }
    }

    [fileArray release];
    [newPath release];
    [pool drain];
    return 0;
}
// ------------------------------------------------------------------- **

cheers gary

+2  A: 

You would use -[NSFileManager fileAttributesAtPath:traverseLink:] (or if you are only targeting 10.5+, -[NSFileManager attributesOfItemAtPath:error:]), and then read the NSFileSize from the returned dictionary.

smorgan
Can I work that into my for(filename ... loop, just not sure as a beginner how I might work that into my existing code?
fuzzygoat
Yes. You would have to, in fact. By the way, remember that the pathnames yielded by `enumeratorAtPath:` are relative to the directory you're enumerating. They're not absolute pathnames, so you can't just collect them into an array and use them later out of context. Use `stringByAppendingPathComponent:` to fuse the leaf path to the directory path.
Peter Hosey