iPhone Dev Resources

Create a temporary file in a safe location

While working on an application to record sounds I was in need for a temporary file location to store the recorded audio in. I wrote a simple method to return an URL to a non existing file in the temporary directory. A file with a name based on the template recording-XXXXXX.caf will be generated in the directory specified by NSTemporaryDirectory(), where XXXXXX will be replaced to create a unique name.

From the mkstemp man pages:

The mktemp() function takes the given file name template and overwrites a portion of it to
create a file name. This file name is guaranteed not to exist at the time of function invocation
and is suit-able suitable able for use by the application.

The file name generated is transformed back to a NSString and then again to a NSURL.

- (NSURL *) tmpFile {
    NSString *tempFileTemplate = [NSTemporaryDirectory() 
        stringByAppendingPathComponent:@"recording-XXXXXX.caf"];
        
    const char *tempFileTemplateCString =
        [tempFileTemplate fileSystemRepresentation];

    char *tempFileNameCString = (char *)malloc(strlen(tempFileTemplateCString) + 1);
    strcpy(tempFileNameCString, tempFileTemplateCString);
    int fileDescriptor = mkstemps(tempFileNameCString, 4);
    
    // no need to keep it open
    close(fileDescriptor);
    
    if (fileDescriptor == -1) {
        NSLog(@"Error while creating tmp file");
        return nil;
    }
    
    NSString *tempFileName = [[NSFileManager defaultManager] 
        stringWithFileSystemRepresentation:tempFileNameCString 
        length:strlen(tempFileNameCString)];
        
    free(tempFileNameCString);
    
    NSLog(@"File path: %@", tempFileName);
    
    return [NSURL fileURLWithPath:tempFileName];
}

Inspired by:
http://cocoawithlove.com/2009/07/temporary-files-and-folders-in-cocoa.html

mkstemps man pages
http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/mktemp.3.html


Add a comment