考虑:
- (void) write: (NSString *) xId data:(NSData *) data forClass: (Class) c {
NSFileManager * fm = [NSFileManager defaultManager] ;
NSString * instancePath = [self instancePath:xId forClass: c] ;
errno = 0 ;
BOOL success = [fm createFileAtPath: instancePath
contents: data
attributes: nil] ;
if (!success) {
::NSLog(@"Couldn't write to path: %@", instancePath) ;
::NSLog(@"Error was code: %d - message: %s", errno, strerror(errno));
} else {
::NSLog(@"COULD write to path: %@", instancePath) ;
::NSLog(@"Error was code: %d - message: %s", errno, strerror(errno));
}
}
然后打印:
2013-03-22 18:59:27.177 otest[18490:303] COULD write to path: /Users/verec/Library/Application Support/iPhone Simulator/6.1/Documents/cal/ModelRepo/ModelRepo#0.sexp
2013-03-22 18:59:27.177 otest[18490:303] Error was code: 3 - message: No such process
2013-03-22 18:59:27.178 otest[18490:303] Couldn't write to path: /Users/verec/Library/Application Support/iPhone Simulator/6.1/Documents/cal/ModelContainer/20130322.sexp
2013-03-22 18:59:27.178 otest[18490:303] Error was code: 3 - message: No such process
这是在运行OCUnit测试时,Xcode 4.6.1 模拟器运行iOS 6.1
我只是感到困惑: - (
答案 0 :(得分:3)
如果调用失败,errno
变量通常仅由系统调用(和某些库函数)设置。如果系统调用成功,则不会修改它,并且可能包含先前错误的非零值。
应在系统调用失败后立即打印或保存errno
。在你的情况下,
NSLog(@"Couldn't write to path: %@", instancePath);
实际上修改了errno。 (“没有这样的过程”不太可能是正确的失败原因。)
errno
在createFileAtPath
失败后包含正确的值。它确实在我的测试中做到了,但它
未记录此方法正确设置/保留errno
。答案 1 :(得分:1)
我正在编写此答案,以使用代码blob更详细地解决verec的错误代码。他在接受答案的评论中实际上暗示了这一点。
他从createFileAtPath
获得的错误是3 (ESRCH) - No Such Process
可能出现这种情况的一个原因是createFileAtPath
不会创建中间目录,因此如果您要创建的路径上的目录不存在,则会因此错误而失败代码。
相反,您必须先使用createDirectoryAtPath:withIntermediateDirectories:attributes:error:
创建目录,然后在成功创建目录后再使用createFileAtPath
。
NSString *fileParentFolderPath;
NSString *filePath;
//first create the directory, createFileAtPath can't create intermediate dirs
NSError *error;
if([[NSFileManager defaultManager] createDirectoryAtPath:fileParentFolderPath
withIntermediateDirectories:YES attributes:nil error:&error]) {
//then create the file
if(![[NSFileManager defaultManager] createFileAtPath:filePath
contents:nil attributes:nil]) {
NSLog(@"Faliure creating File error was code: %d - message: %s", errno, strerror(errno));
};
} else {
NSLog(@"Faliure creating dir w error: %@", error);
};