繁体   English   中英

如何在Mac OS X上获取默认临时目录?

[英]How do I get the default temporary directory on Mac OS X?

我想为某些单元测试创​​建一些数据目录,我希望这些目录位于用户的默认临时目录中。

我想在/ tmp下我可以创建一个子目录,但我不想假设有人建立了自己的机器。

我正计划动态编写测试数据,这就是为什么我想把它放到一个临时目录中。

不要使用tmpnam()tempnam() 它们不安全(有关详细信息,请参见手册页 )。 不要假设/tmp 使用NSTemporaryDirectory()连同mkdtemp() NSTemporaryDirectory()将为您提供更好的目录,但它可以返回nil 我使用过类似的代码:

NSString * tempDir = NSTemporaryDirectory();
if (tempDir == nil)
    tempDir = @"/tmp";

NSString * template = [tempDir stringByAppendingPathComponent: @"temp.XXXXXX"];
NSLog(@"Template: %@", template);
const char * fsTemplate = [template fileSystemRepresentation];
NSMutableData * bufferData = [NSMutableData dataWithBytes: fsTemplate
                                                   length: strlen(fsTemplate)+1];
char * buffer = [bufferData mutableBytes];
NSLog(@"FS Template: %s", buffer);
char * result = mkdtemp(buffer);
NSString * temporaryDirectory = [[NSFileManager defaultManager]
        stringWithFileSystemRepresentation: buffer
                                    length: strlen(buffer)];

您现在可以在temporaryDirectory创建文件。 删除NSLogs以获取生产代码。

回顾那里的这个问题以及NSTemporaryDirectory()的文档,如果您使用的是10.6或更高版本,那么建议您使用URLForDirectory:inDomain:properForURL:create:error: NSFileManager中的方法,以获得更灵活的创建目录的方法。

它返回一个URL而不是一个字符串路径,这是我们建议使用的另一件事。

在Objective-C中,您可以使用NSTemporaryDirectory()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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