Can I use tempnam with iOS?

I am migrating C ++ lib to iOS and run into a problem when the code calls tmpnam. The function returns "var / tmp / tmp.0.0xGlzv", which, I believe, is outside the "sandbox" that is allowed to play in my application. The fopen count returns "Operation not allowed." Is there a viable replacement?

+3
source share
4 answers

What about

[NSTemporaryDirectory() stringByAppendingPathComponent:@"myTempFile1.tmp"];

?

For a unique file name, try something like this:

NSString *uniqueTempFile()
{
    int i = 1;
    while (YES)
    {
        NSString *currentPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%i.tmp", i]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:currentPath])
            return currentPath;
        else
        {
            i++;
        }
    }
}

This is a simple, but probably not the most memory efficient answer.

+3
source

, iostreams, , , , , , , , 't .

- tmpfile (man tmpfile), , , C-style FILE*, iostreams. , , , , , FILE*.

+1

, , ( , , ):

char *td = strdup([[NSTemporaryDirectory() stringByAppendingPathComponent:@"XXXXXX"] fileSystemRepresentation]);
int fd = mkstemp(td);
if(fd == -1) {
    NSLog(@"OPEN failed file %s %s", td, strerror(errno));
}
free(td);
+1

Here is what I use. In addition, it is configured so that you can copy / paste a line without calling a function.

- (NSString *)tempFilePath
{
    NSString *tempFilePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (;;) {
        NSString *baseName = [NSString stringWithFormat:@"tmp-%x.caf", arc4random()];
        tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:baseName];
        if (![fileManager fileExistsAtPath:tempFilePath])
            break;
    }
    return tempFilePath;
}
+1
source

All Articles