1

我正在尝试使用绝对路径打开文件。我的应用程序使用objective-c发送它想要打开的文件,并使用C打开它。我尝试使用它打开它

NSString *str = [[NSString alloc]init];
NSOpenPanel *o = [[NSOpenPanel alloc]init];
[o setAllowsMultipleSelection:NO];
[o setCanChooseDirectories:NO];
[o setCanChooseFiles:YES];
[o setPrompt:@"Open"];
if ([o runModal] == NSOKButton )
{
    // Get an array containing the full filenames of all
    // files and directories selected.
    NSArray* files = [o URLs];

    // Loop through all the files and process them.
    int i;
    for( i = 0; i < [files count]; i++ )
    {
        NSString* fileName = [[files objectAtIndex:i] absoluteString];
        NSLog(@"%@", fileName);

        str = [NSString stringWithFormat:@"%s", openFile([fileName UTF8String])];
        self.tv.string = str;
    }

}

openfile 方法是这样的

char *openFile(const char file[1024]){
FILE *f = fopen(file, "r");
static char c[1000];
char *d;
if (f!=NULL) {
    if (fgets(c, 1000, f) !=NULL){
        d = c;
    }
    else{
        d = "No text";
    }
}
else{
    d="error";
    perror(f);
}
fclose(f);

return d;
}

它发送一个绝对路径file://localhost/Users/macuser/test.txt,但perror(f); 返回No such file or directory。为什么当我知道文件存在时会发生这种情况?

4

1 回答 1

4

file://localhost/Users/macuser/test.txt是 URI,而不是文件路径。处理字符串以删除所有内容,包括在内/localhost,应该没问题。

请注意,这种解决方案只有在 URI 中没有转义序列时才有效。如下所述,从 Objective C 端发送路径可能更简单。

于 2013-03-09T17:04:14.417 回答