2

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

4

2 回答 2

3

提供的代码是 Cocoa 中确定卷上可用空间的最佳方式。只需确保提供给 [NSFileManagerObj fileSystemAttributesAtPath] 的路径包含卷的完整路径。我正在删除最后一个路径组件,以确保传递了一个文件夹而不是一个文件,这导致 /Volumes 被用作没有给出正确结果的文件夹。

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

unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue];    
于 2008-11-06T15:39:17.377 回答
1

statfs 与 df 的结果一致。理论上 NSFileSystemFreeSize 来自 statfs,所以你的问题不应该存在。

您可能希望运行如下 statfs 来替代 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);
}
于 2008-11-05T06:38:00.153 回答