objective-c - xcode文件打开原生C

标签 objective-c c file file-io path

在 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/

相关文章:

ios - 了解复杂的 block 语法

C 快速将字符数组按字母顺序排序

c - C 中的内存溢出

python - 将 txt 文件导入二维 float 列表

php - 如何在php中修改或删除文本文件的一行?

ios - 如何将 unicode 字符放入 NSString

objective-c - 控制声音的速度xcode

bash - 在 bash 文件末尾添加换行符

objective-c - 设置类(class)的区别?

c - scanf 由于 gets 函数而无法正确读取