繁体   English   中英

SDL2 Mac文件处理

[英]SDL2 Mac File Handling

我在Mac上通过SDL2访问文件时遇到了一个奇怪的问题。 我在OS X Mountain Lion上使用XCode 4,我使用SDL2作为框架。 我不是从源代码编译SDL2。 我已经将框架添加到了包中,以及我需要加载的文件。 该程序从XCode构建并运行良好,但文件不会在编辑器外部加载(IE如果我双击独立的.app文件不加载)。 这是我的.app包的样子:

MyApp.app/
    Contents/
        Frameworks/
            SDL2.framework/
        MacOS/
            MyApp
        Resources/
            Configure.txt
            MyBMP.bmp
        Info.plist
        PkgInfo

在我的C代码中,我试过这个:

SDL_LoadBMP("MyApp.app/Contents/Resources/MyBMP.bmp");

就这样:

SDL_LoadBMP("MyBMP.bmp");

几乎所有东西都在中间。 我也试过通过以下方式访问文本文件:

FILE* data = fopen("MyApp.app/Contents/Resources/Configure.txt", "r");

FILE* data = fopen("Configure.txt", "r");

没有成功。 在XCode编辑器中,只有长绝对路径可以工作,而我尝试的任何东西都没有在独立的.app中工作。

其他人是否遇到过这个问题? 我在使用SDL 1.2时加载了文件,但由于某些原因,似乎没有任何东西加载SDL2。 在初始化期间,SDL2是否对活动目录做了一些奇怪的事情?

-------------编辑1 --------------我最近试图找出正在发生的事情使用了这段代码:

#include "SDL2/SDL.h"
#include "stdio.h"
#include "stdlib.h"

int main (int argc, char** argv){
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
         return EXIT_FAILURE;

    FILE* test = fopen("Test.txt", "w");

    if (!test) 
        return EXIT_FAILURE;

    fprintf(test, "Let's see where this ends up...");
    fclose(test);
    return EXIT_SUCCESS;

    //The rest of my code, which shouldn't ever come into play...
}

从XCode 4编辑器运行时,这可以按预期工作。 在Debug文件夹中,在我的.app文件旁边,有一个Test.txt文件,其中包含短语“让我们看看它最终会在哪里......”。 但是,当通过单击独立应用程序运行时,程序立即结束,并且没有找到文本文件。 我已经检查了日志,它只是说程序退出了代码1.通过更彻底的分析,似乎fopen()失败了。 有没有人知道可能会发生什么?

您可以使用以下命令将工作目录设置为应用程序包中的Resources目录:

#include "CoreFoundation/CoreFoundation.h"

char path[PATH_MAX];
CFURLRef res = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle());
CFURLGetFileSystemRepresentation(res, TRUE, (UInt8 *)path, PATH_MAX)
CFRelease(res);
chdir(path);

您可能希望在#ifdef __APPLE__#endif之间进行换行以实现跨平台兼容性。

下载ResourcePath.hpp的SFML库或从https://github.com/Malaxiz/Third/blob/network/Fifth/ResourcePath.hpp获取它https://github.com/Malaxiz/Third/blob/network/Fifth /ResourcePath.mm

#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#include "ResourcePath.hpp"
#endif

void CGame::_initRelativePaths() {
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
    char path[PATH_MAX];
    if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
    {
        // error!
    }
    CFRelease(resourcesURL);

    chdir(path);
    #endif
    // ---------------------------------------------------------------------------    -
}

在init中运行该函数。

参考: https//github.com/Malaxiz/Third/blob/network/Fifth/CGame.cpp#L191

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM