Apparently, NSFileManager
is unable to delete files created by mkstemp()
. Here's some test code to demonstrate this:
char pathCString[] = "/tmp/temp.XXXXXX";
int fileDescriptor = mkstemp(pathCString);
if (fileDescriptor == -1) {
NS开发者_StackOverflowLog(@"mkstemp failed");
} else {
close(fileDescriptor);
NSURL *url = [NSURL URLWithString:[NSString stringWithCString:pathCString encoding:NSASCIIStringEncoding]];
NSLog(@"URL: %@", url);
NSError *error;
if (![[NSFileManager defaultManager] removeItemAtURL:url error:&error]) {
NSLog(@"could not delete file: %@", error);
}
}
Here's what I see in the log when I run the above code:
URL: /tmp/temp.A7DsLW
could not delete file: Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x1001108a0 "The file “temp.A7DsLW” doesn’t exist."
I'm running this on Snow Leopard. Any ideas on why the problem is occurring and/or how to work around it?
Thanks!
Don't use -URLWithString:, use -fileURLWithPath: you didn't make a valid file URL. Passing the path string directly to NSFileManager's -removeItemAtPath: will of course be shorter.
Also, for file paths, always make the path string with -stringWithUTF8String:.
精彩评论