T
T
Toly2016-10-02 22:50:35
Cocoa
Toly, 2016-10-02 22:50:35

How to find out the size of a directory, package, etc. in the COCOA API?

Finding out the file size in the COCOA API is pretty easy, for example:

NSNumber *value = nil;
[url getResourceValue:&value forKey:NSURLFileSizeKey error:nil];
NSUInteger size = [value unsignedLongLongValue];
NSLog(@"File size: %li", size);

But here's how, in about the same simple way, you can find out the size of the directory?
Now, to get the size of the directory, I use the recursive enumeration method, like this:
off_t sizeForFolderStat(const char *path)
{
    off_t size = 0;
    
    DIR *directory;
    directory = opendir(path);
    
    if (directory == NULL) {
        fprintf(stderr, "could not open directory '%s'\n", path);
        fprintf(stderr, "error is %d/%s\n", errno, strerror(errno));
        exit (EXIT_FAILURE);
    }
    
    struct dirent *entry;
    while ( (entry = readdir(directory)) != NULL) {
        char filename[MAXPATHLEN];
        int result;
        struct stat statbuf;
        
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        snprintf(filename, MAXPATHLEN, "%s/%s", path, entry->d_name);
        
        result = lstat(filename, &statbuf);
        if (result != 0) {
            fprintf (stderr, "could not stat '%s': %d/%s\n", entry->d_name, errno, strerror(errno));
            continue;
        }
        
        if (S_ISDIR(statbuf.st_mode)) {
            size += sizeForFolderStat(filename);
        } else {
            size += statbuf.st_size;
        }
    }
    
    closedir(directory);
    
    return size;  
}

This function is quite fast, but when a directory contains a lot of attachments it can be very CPU intensive.
Looking for easy ways to get the size of a directory, I found that using a class NSMetadataItem, you can get the size of the application very simply and quickly:
NSUInteger size = 0;
NSNumber *isApp;
 [url getResourceValue:&isApp forKey:NSURLIsApplicationKey error:nil];
if ([isApp boolValue]) {
    NSMetadataItem *metadata = [[NSMetadataItem alloc] initWithURL:url];
    size = [[metadata valueForAttribute:@"kMDItemFSSize"] unsignedLongLongValue];
 }

In fact, .app is also a directory, but for ordinary directories (folders) or packages, this method returns only the size of the folder (about 4Kb), and not the full size of the directory, including the size of all its contents.
I suspect that packages or directories (folders) also have similar ways - quickly and easily get the size of the directory including the size of all its contents.
If anyone knows how to do this please share your experience.
Or tell me how you get the size of directories?
Thank you all in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question