Can I use tempnam with IOS?
I'm porting a C++ lib to iOS, and have run into an issue where the code calls tmpnam. The function returns "var/tmp/tmp.0.0xGlzv" which I assume is outside of the "sandbox" that my app is allowed to play in. A subsquent fopen returns "Oper开发者_如何学编程ation not permitted". Is there a viable replacement?
What about
[NSTemporaryDirectory() stringByAppendingPathComponent:@"myTempFile1.tmp"];
?
For a unique filename, 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 simple, but probably not the most memory-efficent answer.
I'm not aware of any replacement that you can use with iostreams, but recall that using functions that return a name that you open later expose you to race conditions where another process opens the file simultaneous to your program determining that it doesn't exist.
Safer is to use something like tmpfile
(man tmpfile) which unfortunately returns a C-style FILE*
rather than allowing you to use iostreams. It would be trivial however to write a class that wraps using a stringstream and then writing the contents of that stream as text to the FILE*
.
I believe this is what you really want (file has no extension so append one if you want):
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);
Here's what I'm using. Also, this is set up so you can copy/paste inline without the function call.
- (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;
}
精彩评论