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

Abi*_*ern 23 macos cocoa test-data objective-c temporary-directory

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

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

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

Dav*_*bin 39

不要使用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)];
Run Code Online (Sandbox Code Playgroud)

您现在可以在里面创建文件temporaryDirectory.删除NSLogsfor生产代码.


Abi*_*ern 8

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

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


小智 6

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


Jas*_*ers 5

使用tempnam(),tmpnam()或tmpfile()函数.

  • tempnam()和tmpnam()是不安全的.请改用mkstemp(). (2认同)