Joannes
Joannes

Reputation: 81

Get file size given a path

I'm new in objective-c. I have a path to file contained in an NSString and I want get file size. I found this example and change deprecated code with attributesOfItemAtPath:error: but path is always invalid.

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = @"~/Library/Safari/History.plist";
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath: path error: NULL];


if (fileAttributes != nil) {
    NSNumber *fileSize;

    if (fileSize == [fileAttributes objectForKey:NSFileSize]) {
        NSLog(@"File size: %qi\n", [fileSize unsignedLongLongValue]);
    }

}
else {
    NSLog(@"Path (%@) is invalid.", pPath);
}
[NSFileManager release];

Upvotes: 2

Views: 7716

Answers (5)

Raunak
Raunak

Reputation: 3414

Your Path will always be invalid because of a super-silly bug in your code.

Change

if (fileSize == [fileAttributes objectForKey:NSFileSize]) {

to

if (fileSize = [fileAttributes objectForKey:NSFileSize]) {

I hope no further explanatiuon would be required.

Upvotes: 1

Maulik
Maulik

Reputation: 19418

you can get size by :

NSDictionary * properties = [[NSFileManager defaultManager] attributesOfItemAtPath:yourFilePath error:nil];
NSNumber * size = [properties objectForKey: NSFileSize];

size is a NSNumber that contains a unsigned long long.

Upvotes: 1

Sylter
Sylter

Reputation: 1623

This should work:

uint64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:_filePath error:nil] fileSize];

It's very similar to the one used by you, but in yours there's a mistake: you put NULL instead of nil in the error: handling.

Make sure also to expand tilde in your path, as explained in the documentation: use stringByExpandingTildeInPath, so your NSString *path should be something like this:

NSString *path = [[NSString stringWithString:@"~/Library/Safari/History.plist"] stringByExpandingTildeInPath];

Here you can find some explanations about the difference between nil and NULL.

Upvotes: 4

Chris Ledet
Chris Ledet

Reputation: 11628

Use the defaultManager class method on NSFileManager instead of creating your own instance. Also, do not include ~ (tilde) symbol in your file path. Use the NSHomeDirectory() function to get the home directory instead. Here's an example:

NSString *path = [NSString stringWithFormat:@"%@/Library/Safari/History.plist", NSHomeDirectory()];
[[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize];

This should return the size of your file.

Upvotes: 0

user1118321
user1118321

Reputation: 26395

You might need to expand the path using:

 - (NSString *)stringByExpandingTildeInPath

Upvotes: 1

Related Questions