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.