我正在尝试下面的代码,看看我是否可以让它扩展这些位置的绝对路径,以便我可以将它们用于 NSFileManager 的操作,当我使用波浪号和相对路径时,这些操作会失败。
我正在使用 Objective-C 中的 Xcode 开发命令行应用程序。我可以从命令行运行该程序,它为我扩展了路径,但是从 Xcode 中的目标,我使用 $PROJECT_DIR 和 $HOME 传递命令行参数的值,以便让我参与其中。问题是我需要访问 $PROJECT_DIR/.. 这不是通过 NSFilemanager 解决的。
URLByResolvingSymlinksInPath 或 URLByStandardizingPath 似乎没有像我预期的那样工作。还有什么我应该做的吗?
BOOL isDir = TRUE;
for (NSString *path in @[@"~/", @".", @".."]) {
NSURL *url = [[[NSURL URLWithString:path] URLByResolvingSymlinksInPath] URLByStandardizingPath];
DebugLog(@"path: %@", url.absoluteString);
DebugLog(@"Exists: %@", [[NSFileManager defaultManager] fileExistsAtPath:url.path isDirectory:&isDir] ? @"YES" : @"NO");
}
更新:我使用来自 stdlib 的 realpath 来解析路径并创建了以下方法,尽管我不理解这个 C 函数。具体来说,我不知道解析的值是什么或我将如何使用它。我确实看到了得到预期的返回值。
- (NSString *)resolvePath:(NSString *)path {
NSString *expandedPath = [[path stringByExpandingTildeInPath] stringByStandardizingPath];
const char *cpath = [expandedPath cStringUsingEncoding:NSUTF8StringEncoding];
char *resolved = NULL;
char *returnValue = realpath(cpath, resolved);
// DebugLog(@"resolved: %s", resolved);
// DebugLog(@"returnValue: %s", returnValue);
return [NSString stringWithCString:returnValue encoding:NSUTF8StringEncoding];
}