在 Xcode 库项目中,我有一个 native .c 文件,我需要在其中打开来自应用程序包或文档部分的文本文件。
在 Objective-C 中我可以做:
[[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
但这在原生 C 中不起作用。
我需要使用:
FILE *fp = fopen("data.txt", "rb");
但我不确定如何获取“data.txt”文件的路径。
最佳答案
如果你想完全留在 C 中,那么你可以链接到 Core Foundation 并执行类似的操作:
#include "read_data.h"
#include <stdio.h>
#include <CoreFoundation/CoreFoundation.h>
char * CFStringCopyUTF8String(CFStringRef aString) {
if (aString == NULL) {
return NULL;
}
CFIndex length = CFStringGetLength(aString);
CFIndex maxSize =
CFStringGetMaximumSizeForEncoding(length,
kCFStringEncodingUTF8);
char *buffer = (char *)malloc(maxSize);
if (CFStringGetCString(aString, buffer, maxSize,
kCFStringEncodingUTF8)) {
return buffer;
}
return NULL;
}
int open_data_file(void)
{
FILE *fp;
CFBundleRef mainBundle = CFBundleGetMainBundle();
if( mainBundle == NULL )
{
printf("unable to get main bundle\n");
return -1;
}
CFURLRef dataFileURL = CFBundleCopyResourceURL(mainBundle, CFSTR("data"), CFSTR("txt"), NULL);
if( dataFileURL == NULL )
{
printf("unable to locate data file\n");
return -1;
}
CFStringRef path;
if( !CFURLCopyResourcePropertyForKey(dataFileURL, kCFURLPathKey, &path, NULL))
{
printf("unable to get file path\n");
return -1;
}
char *pathBuffer = CFStringCopyUTF8String(path);
fp = fopen(pathBuffer, "rb");
free(pathBuffer);
return 1;
}
为清楚起见,省略了一些错误检查等。
关于objective-c - xcode文件打开原生C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20283054/