简体   繁体   English

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

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

I'd like to create some directories of data for some unit tests and I'd like these directories to be in the default temporary directory for the user. 我想为某些单元测试创​​建一些数据目录,我希望这些目录位于用户的默认临时目录中。

I could just create a subdir under /tmp I suppose, but I don't want to make an assumption about how somebody has set up their own machine. 我想在/ tmp下我可以创建一个子目录,但我不想假设有人建立了自己的机器。

I'm planning on writing the test data on the fly, which is why I'd like to put this into a temporary directory. 我正计划动态编写测试数据,这就是为什么我想把它放到一个临时目录中。

Don't use tmpnam() or tempnam() . 不要使用tmpnam()tempnam() They are insecure (see the man page for details). 它们不安全(有关详细信息,请参见手册页 )。 Don't assume /tmp . 不要假设/tmp Use NSTemporaryDirectory() in conjunction with mkdtemp() . 使用NSTemporaryDirectory()连同mkdtemp() NSTemporaryDirectory() will give you a better directory to use, however it can return nil . NSTemporaryDirectory()将为您提供更好的目录,但它可以返回nil I've used code similar to this: 我使用过类似的代码:

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

You can now create files inside temporaryDirectory . 您现在可以在temporaryDirectory创建文件。 Remove the NSLogs for production code. 删除NSLogs以获取生产代码。

Looking back at this question there and the documentation for NSTemporaryDirectory(), if you are using 10.6 or above, then you are recommended to use the URLForDirectory:inDomain:appropriateForURL:create:error: method from NSFileManager for a more flexible method of creating directories. 回顾那里的这个问题以及NSTemporaryDirectory()的文档,如果您使用的是10.6或更高版本,那么建议您使用URLForDirectory:inDomain:properForURL:create:error: NSFileManager中的方法,以获得更灵活的创建目录的方法。

And it returns a URL instead of a string path, which is another thing we're recommended to use. 它返回一个URL而不是一个字符串路径,这是我们建议使用的另一件事。

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

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

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