You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XCode中C++开发iOS游戏时无法写入文件的问题求助

解决方案

iOS系统中,App的主Bundle(即你通过Xcode复制到设备的资源目录)是只读的,任何尝试写入Bundle内文件的操作都会被系统拒绝,这就是你遇到"Operation not permitted"错误的核心原因。

正确的处理流程是:

  1. 首次启动App时,将Bundle中的初始存档文件复制到App的Documents目录(该目录为可读写区域,且默认会被iCloud备份)
  2. 后续所有的读、写操作都针对Documents目录下的存档文件

具体实现步骤

1. 获取Documents目录路径

可以通过Objective-C代码获取路径后传递给C++模块:

// Objective-C代码,获取Documents目录的C风格字符串路径
NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
const char *docsCPath = [documentsDir UTF8String];

若需纯C++实现,可通过环境变量获取:

const char *homeDir = getenv("HOME");
std::string documentsPath = std::string(homeDir) + "/Documents/";

2. 复制初始存档到Documents目录

假设Bundle中的初始存档文件名为save.dat,先获取其Bundle内路径,再执行复制:

// 假设bundleSavePath是从Objective-C传递来的Bundle内存档路径
void CopyInitialSave(const std::string& bundleSavePath, const std::string& docsPath) {
    std::string targetPath = docsPath + "save.dat";
    // 先检查目标路径是否已存在存档,避免重复复制
    std::ifstream checkFile(targetPath);
    if (checkFile.good()) {
        checkFile.close();
        return;
    }
    checkFile.close();

    // 从Bundle复制到Documents
    std::ifstream src(bundleSavePath, std::ios::binary);
    std::ofstream dst(targetPath, std::ios::binary);
    if (src && dst) {
        dst << src.rdbuf();
    }
    src.close();
    dst.close();
}

3. 修改读写逻辑指向Documents路径

将你的mSavePath替换为Documents目录下的存档路径:

mSavePath = documentsPath + "save.dat";

之后的LoadProgress和SaveProgress操作该路径即可正常读写。

注意事项

  • 不要尝试修改Bundle内文件的权限,iOS系统严格禁止此类操作
  • Documents目录是App的私有可读写目录,完全适配存档类数据的存储需求
  • 若不需要iCloud备份,可考虑使用Library/Caches目录,但存档数据通常存放在Documents更合适

内容的提问来源于stack exchange,提问作者Ludius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:35:23