Chris Loonam
Chris Loonam

Reputation: 5745

C fopen can't open absolute path OS X

I'm trying to open a file using an absolute path. My app sends what file it wants opened using objective-c, and opens it using C. I try to open it using this

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;
    }

}

the openfile method is this

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;
}

it sends an absolute path like file://localhost/Users/macuser/test.txt, but the perror(f); returns No such file or directory. Why does this happen when I know the file exists?

Upvotes: 1

Views: 1329

Answers (1)

teppic
teppic

Reputation: 8195

file://localhost/Users/macuser/test.txt is a URI, not a file path. Process the string to strip out everything up to and including /localhost and it should be fine.

Note that this sort of solution will only work if there are no escape sequences in the URI. As noted below, it may be simpler to send the path from the Objective C side.

Upvotes: 4

Related Questions