简体   繁体   中英

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

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM