【问题标题】:C fopen can't open absolute path OS XC fopen 无法打开绝对路径 OS X
【发布时间】:2013-03-09 16:59:22
【问题描述】:

我正在尝试使用绝对路径打开文件。我的应用程序使用 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。为什么我知道文件存在时会发生这种情况?

【问题讨论】:

    标签: objective-c c fopen


    【解决方案1】:

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

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

    【讨论】:

    • URI 也可能包含 % 转义,因此像这个答案提出的幼稚转换并不是一个好的通用解决方案。
    • @R..:我提供了一种简单的方法来完成问题中所要求的操作,但是是的,对于一般解决方案,需要更多处理,但如上所述,从ObjC 方面。
    猜你喜欢
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2011-08-16
    • 1970-01-01
    • 2018-02-02
    • 2011-04-04
    相关资源
    最近更新 更多