Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to get size of folder (ObjC/Cocoa)?

Right now I'm using this code to get the size of a folder:

NSArray *contents;
        NSEnumerator *enumerator;
        NSString *path;
        contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
        enumerator = [contents objectEnumerator];
        while (path = [enumerator nextObject]) {
            NSDictionary *fattrib = [[NSFileManager defaultManager] fileAttributesAtPath:[folderPath stringByAppendingPathComponent:path] traverseLink:YES];
            fileSize +=[fattrib fileSize];
        }

        [contents release];
        [path release]; 

The problem is that its highly innacurate. It either adds a few megabytes or deducts a few megabytes from the actual size. For example I got the file size of an .app bundle and this method reported 16.2MB, whereas the actual thing is 15.8.

What's the best way to get the size of a folder?

Thanks

like image 701
indragie Avatar asked Aug 14 '09 01:08

indragie


People also ask

How can I see folder size?

Go to Windows Explorer and right-click on the file, folder or drive that you're investigating. From the menu that appears, go to Properties. This will show you the total file/drive size. A folder will show you the size in writing, a drive will show you a pie chart to make it easier to see.


1 Answers

I needed to do this today myself, and I've found that the code in this post on the Cocoa-dev list is super fast and matches what Finder says to the byte. (don't forget to OR in the kFSCatInfoRsrcSizes flag so you get resource fork sizes, too!)

If you need more explanation on how to use it, just leave a comment and I'll edit this post. =)

like image 55
Dave DeLong Avatar answered Nov 07 '22 23:11

Dave DeLong