本文共 1326 字,大约阅读时间需要 4 分钟。
Objective-C 实现获取磁盘剩余空间
要获取设备磁盘的剩余空间,可以使用 NSFileManager 提供的方法 attributesOfFileSystemForPath:error: 来获取文件系统的属性,其中包括可用空间和总空间信息。以下是一个完整的 Objective-C 源码示例,演示了如何获取并打印磁盘的总空间和剩余空间。
以下代码是一个简单的命令行工具,您可以在 macOS 上的 Xcode 中创建一个新的 “macOS Command Line Tool” 项目,并将 main.m 文件替换为以下内容:
#importint main(int argc, char **argv) { NSFileManager *fileManager = [NSFileManager new]; NSError *error = [NSError new]; // 获取根目录的文件系统属性 [fileManager attributesOfFileSystemForPath:@"/" error:error]; if (error) { NSLog(@"获取文件系统属性失败: %@", [error localizedDescription]); return NSRUNTIMEERROR; } // 打印总空间和剩余空间 NSFileSystemAttributes *attributes = [fileManager attributesOfFileSystemForPath:@"/" error:nil]; NSLog(@"磁盘总空间: %lld MB,剩余空间: %lld MB,使用率: %.0f%%", (long long)[attributes fileSize], (long long)[attributes freeSpace], ([attributes fileSize] * 100) / [attributes fileSize]); return EXIT_SUCCESS;}
在 Xcode 中创建一个新的项目,选择 “macOS Command Line Tool” 类型,项目名称可以设置为 “磁盘空间检查” 或其他合适的名称。
将上述代码复制到新的 main.m 文件中,确保包含必要的导入声明。
使用 Xcode 编译项目,并在终端中运行可执行文件。您将看到磁盘的总空间、剩余空间以及使用率的百分比。
转载地址:http://zbsfk.baihongyu.com/