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

M1 Mac下使用boost::filesystem创建目录报Illegal byte sequence错误求助

Boost Filesystem 在 M1 Mac 上创建目录时出现「Illegal byte sequence」错误的解决方案

你的代码:

boost::filesystem::path dir("./results");
if (!boost::filesystem::exists(dir)) {
    boost::filesystem::create_directory(dir);
}

运行时错误:

boost::filesystem::create_directory: Illegal byte sequence [system:92]: "@��l"

从你提供的path对象内部状态来看,_M_local_buf包含无效字符./results/\0o\U00000001,说明路径对象内存已被污染,或者Boost与Apple Silicon macOS的编码兼容存在问题。以下是具体解决方法:

  • 升级Boost到兼容Apple Silicon的版本
    旧版本Boost(如1.74及以下)对ARM64架构macOS支持不完善,易出现编码和路径处理异常。建议升级到Boost 1.75或更高版本,可通过Homebrew安装:

    brew install boost
    
  • 强制Boost使用UTF-8编码
    macOS默认使用UTF-8编码,但Boost Filesystem可能未正确继承系统locale,手动设置全局locale并注入到path对象:

    #include <locale>
    #include <boost/filesystem.hpp>
    
    int main() {
        // 设置全局locale为UTF-8
        std::locale::global(std::locale("en_US.UTF-8"));
        // 让Boost Filesystem使用该locale处理路径编码
        boost::filesystem::path::imbue(std::locale());
    
        boost::filesystem::path dir("./results");
        if (!boost::filesystem::exists(dir)) {
            bool created = boost::filesystem::create_directory(dir);
            if (!created) {
                // 可选:打印更详细的错误信息
                std::cout << "Error creating directory: " << boost::system::system_error().what() << std::endl;
            }
        }
        return 0;
    }
    
  • 排查内存越界问题
    _M_local_buf中的无效字符大概率是代码中存在内存越界写入、野指针等操作,污染了path对象的内部缓冲区。检查当前代码块前后是否有数组越界、指针错误逻辑,比如:

    • 对char数组的写入超出范围
    • 未初始化的指针指向path对象内存区域
  • 使用绝对路径替代相对路径
    相对路径可能因工作目录编码或环境变量问题出错,尝试拼接绝对路径:

    #include <cstdlib>
    #include <boost/filesystem.hpp>
    
    int main() {
        const char* cwd = std::getenv("PWD");
        if (cwd == nullptr) {
            // 处理获取当前目录失败的情况
            return 1;
        }
        boost::filesystem::path dir(cwd);
        dir /= "results";
    
        if (!boost::filesystem::exists(dir)) {
            boost::filesystem::create_directory(dir);
        }
        return 0;
    }
    
  • 检查编译链接选项
    确保使用Clang(Apple默认编译器)编译,并链接ARM64架构的Boost库:

    • 编译命令示例:
      clang++ -std=c++17 your_code.cpp -o your_program -lboost_filesystem
      

    避免使用x86_64架构的Boost库(如通过Rosetta安装的版本),确保库与程序架构一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 09:47:44