【问题标题】:xcode file open native Cxcode文件打开本机C
【发布时间】:2013-12-15 11:46:23
【问题描述】:

在 Xcode 库项目中,我有一个本机 .c 文件,我需要在其中从应用程序包或文档部分打开一个文本文件。

在 Objective-C 中我可以做到:

[[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

但这不适用于原生 C。

我需要使用:

FILE *fp = fopen("data.txt", "rb");

但我不确定如何获取“data.txt”文件的路径。

【问题讨论】:

  • 为什么? C 文件中有哪些内容是您无法修改的,无论是传递文件还是使其成为 Objective-C?
  • 如果您知道文件相对于 bin 的位置,那么相对路径就可以了。如果您正在处理符号链接等,只需use realpath
  • 最简单的方法是将其制作为 .m 文件并编写 Objective-C 代码。您仍然可以在那里拥有 C 代码。否则,您可以从“外部”获取路径作为参数或呼出。
  • 经过一些变通方法后,将文件操作移至 .m 文件中。但是,在想,如果客户只有本机并且需要实施。

标签: objective-c c file file-io path


【解决方案1】:

如果您想完全留在 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;
}

为了清楚起见,省略了一些错误检查等。

【讨论】:

  • 使用上面的代码,运行时出现以下错误。 dyld:找不到符号:_kCFURLPathKey 引用自:/var/mobile/Applications/3BE03596-268E-4257-B688-9D020049DD9B/theSampleAppn.app/theAudioAppn 预期在:/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation in /var /mobile/Applications/3BE03596-268E-4257-B688-9D020049DD9B/theSampleAppn.app/theSampleAppn
  • 使用上面的代码,运行时出现以下错误。 斜体 dyld:找不到符号:_kCFURLPathKey 引用自:/var/mobile/Applications/3BE03596-268E-4257-B688-9D020049DD9B/theSampleAppn.app/theAudioAppn 预期在:/System/Library/Frameworks/ /var/mobile/Applications/3BE03596-268E-4257-B688-9D020049DD9B/theSampleAppn.app/theSampleAppn 中的CoreFoundation.framework/CoreFoundation 执行环境是,Xcode-5和iOS 7.0框架。该应用程序包含“CoreFoundation.framework”。但它仍然给出错误。你有什么想法吗?
  • 您是否与 Core Foundation 建立了联系? (目标 > 将二进制文件与库链接)
  • 是的,我添加了 Core Foundation 框架,标题也包含在内。
  • 我在github上为你创建了sample project
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多