views:

1234

answers:

4

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.

I'm planning on writing the test data on the fly, which is why I'd like to put this into a temporary directory.

+4  A: 

Use the tempnam(), tmpnam() or tmpfile() function.

Jasper Bekkers
tempnam() and tmpnam() are insecure. Use mkstemp() instead.
Dave Dribin
Maybe not, but at least I found out about TEMPDIR
Abizern
+19  A: 

Don't use tmpnam() or tempnam(). They are insecure (see the man page for details). Don't assume /tmp. Use NSTemporaryDirectory() in conjunction with mkdtemp(). NSTemporaryDirectory() will give you a better directory to use, however it can return 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. Remove the NSLogs for production code.

Dave Dribin
Thanks Dave, that helps me a lot.
Abizern
+2  A: 

In Objective-C you can use NSTemporaryDirectory().

A: 

You may also want to check out this thread.

Philipp