macOS 应用程序无法打开存在的文件
macOS app cannot open file that exists
我在 Xcode 应用程序 (macOS) 中有一个 C 模块可以打开一个文件。
代码如下:
char fname1 [1028] = "/Library/Preferences/tbupdd.ini";
FILE * fp;
fp = fopen(fname1, "r");
if (fp == NULL)
{
perror("error opening updd.ini");
printf("File %s not found, use another method for getting version\n", fname1);
exit(1);
}
该文件存在,我可以在终端中读取它。但是 运行 Xcode 中的这个应用正在提供
error opening updd.ini: Operation not permitted
该文件具有以下权限:
$ ls -l /Library/Preferences/tbupdd.ini
-rw-r--r-- 1 root wheel 25584 20 Dec 15:05 /Library/Preferences/tbupdd.ini
我知道 Xcode 有一个工作目录,但这会影响上面的绝对路径吗?
现代 macOS 应用程序采用沙盒,只允许更新沙盒中的文件。参见 File System Programming Guide: The Library Directory Stores App-Specific Files. Also see About App Sandbox。
我不建议使用这样的硬编码路径。我建议从 NSFileManager
获取库文件夹
NSURL *fileURL = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
NSAssert(!error, @"Unable to get library directory: %@", [error localizedDescription]);
NSLog(@"%s", fileURL.path.UTF8String);
那个returns:
/Users/{username}/Library/Containers/{com.domain.app}/Data/Library
然后您可以将其传递给您的 C 函数。
顺便说一句,Apple 明确建议我们不应在 Preferences
子文件夹中创建文件。他们warn us:
This directory contains app-specific preference files. You should not create files in this directory yourself. Instead, use the NSUserDefaults
class or CFPreferences
API to get and set preference values for your app.
我在 Xcode 应用程序 (macOS) 中有一个 C 模块可以打开一个文件。
代码如下:
char fname1 [1028] = "/Library/Preferences/tbupdd.ini";
FILE * fp;
fp = fopen(fname1, "r");
if (fp == NULL)
{
perror("error opening updd.ini");
printf("File %s not found, use another method for getting version\n", fname1);
exit(1);
}
该文件存在,我可以在终端中读取它。但是 运行 Xcode 中的这个应用正在提供
error opening updd.ini: Operation not permitted
该文件具有以下权限:
$ ls -l /Library/Preferences/tbupdd.ini
-rw-r--r-- 1 root wheel 25584 20 Dec 15:05 /Library/Preferences/tbupdd.ini
我知道 Xcode 有一个工作目录,但这会影响上面的绝对路径吗?
现代 macOS 应用程序采用沙盒,只允许更新沙盒中的文件。参见 File System Programming Guide: The Library Directory Stores App-Specific Files. Also see About App Sandbox。
我不建议使用这样的硬编码路径。我建议从 NSFileManager
NSURL *fileURL = [[NSFileManager defaultManager] URLForDirectory:NSLibraryDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
NSAssert(!error, @"Unable to get library directory: %@", [error localizedDescription]);
NSLog(@"%s", fileURL.path.UTF8String);
那个returns:
/Users/{username}/Library/Containers/{com.domain.app}/Data/Library
然后您可以将其传递给您的 C 函数。
顺便说一句,Apple 明确建议我们不应在 Preferences
子文件夹中创建文件。他们warn us:
This directory contains app-specific preference files. You should not create files in this directory yourself. Instead, use the
NSUserDefaults
class orCFPreferences
API to get and set preference values for your app.