tags:

views:

575

answers:

3

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

A: 

I'm confused. What's wrong with the solution you provide?

Peter Hosey
Sorry, It seems I believed the code provided was not working but that was due to the fact that folder was "/Volumes" rather than "/Volumes/VOlumeName" which would not reflect the size of the actual volume.
AlanKley
A: 

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);
}
diciu
+1  A: 

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];
AlanKley