![](/img/trans.png)
[英]Is there an equivalent of Mac OS X “open” command that can be called from C++/Objective-C code?
[英]C fopen can't open absolute path OS X
我正在嘗試使用絕對路徑打開文件。 我的應用程序使用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
。 當我知道文件存在時,為什么會這樣?
file://localhost/Users/macuser/test.txt
是一個URI,而不是文件路徑。 處理字符串以去除包括/localhost
在內的所有內容,它應該沒問題。
請注意,只有URI中沒有轉義序列時,此類解決方案才有效。 如下所述,從Objective C端發送路徑可能更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.