Joris Kluivers

I like to build software.

Creating Temporary Files in a Safe Location

While working on an application to record sounds I was in need for a temporary file location to write the recorded audio to. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
- (NSString *) 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);

    return tempFileName;
}

Inspired by Temporary files and folders in Cocoa