AlanKley
AlanKley

Reputation: 4780

How do you find the amount of free space on a mounted volume using Cocoa?

I am using the following code to determine free space on a volume. The folder was provided using NSOpenPanel. The item selected was a mounted volume and the path returned is \Volumes\Name

NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];

unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];    

Is there a better method to determine the free space on a mounted volume using Cocoa?

Update: This is in fact the best way to determine the free space on a volume. It appeared it wasn't working but that was due to the fact that folder was actually /Volumes rather than /Volume/VolumeName

Upvotes: 2

Views: 1963

Answers (2)

AlanKley
AlanKley

Reputation: 4780

The code provided IS the best way in Cocoa to determine the free space on a volume. Just make sure that the path provided to [NSFileManagerObj fileSystemAttributesAtPath] includes the full path of the volume. I was deleting the last path component to assure that a folder rather than a file was passed in which resulted in /Volumes being used as the folder which does not give the right results.

NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];

unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];    

Upvotes: 3

diciu
diciu

Reputation: 29333

statfs is consistent with results from df. In theory NSFileSystemFreeSize comes from statfs, so your problem should not exist.

You may want to run statfs as below as a replacement for NSFileSystemFreeSize:

#include <sys/param.h>
#include <sys/mount.h>

int main()
{
    struct statfs buf;

    int retval = statfs("/Volumes/KINGSTON", &buf);

    printf("KINGSTON Retval: %d, fundamental file system block size %ld, total data blocks %d, total in 512 blocks: %ld\n",
            retval, buf.f_bsize, buf.f_blocks, (buf.f_bsize / 512) * buf.f_blocks); 
    printf("Free 512 blocks: %ld\n",  (buf.f_bsize / 512) * buf.f_bfree); 
    exit(0);
}

Upvotes: 1

Related Questions