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

使用bazel run运行cc_binary时未覆盖输出文件的问题咨询

问题分析与解决
  • 这并非Bazel配置遗漏,核心原因是你的C++程序本身未处理文件覆盖逻辑。Bazel执行bazel run时仅负责编译并启动程序,文件写入行为完全由代码自身控制。
  • 若要实现无论out.txt是否存在都覆盖写入,需修改代码逻辑:
    • 使用std::ofstream时,确保指定std::ios::trunc标志(若代码用了std::ios::app等追加模式,会导致不覆盖已有内容)
    • 示例代码:
      #include <fstream>
      int main() {
          // 显式指定trunc确保覆盖已有文件
          std::ofstream outfile("out.txt", std::ios::out | std::ios::trunc);
          if (outfile.is_open()) {
              outfile << "输出内容\n";
              outfile.close();
          }
          return 0;
      }
      
  • 补充:bazel run的默认工作目录是Bazel运行时沙箱,若需将输出文件放到bazel-bin这类Bazel输出目录,可通过$(location)宏传递路径:
    • BUILD文件修改:
      cc_binary(
          name = "my_prog",
          srcs = ["my_prog.cpp"],
          args = ["$(location out.txt)"],
          outputs = ["out.txt"],
      )
      
    • 程序接收命令行参数作为输出路径:
      #include <fstream>
      #include <string>
      int main(int argc, char* argv[]) {
          if (argc < 2) return 1;
          std::string out_path = argv[1];
          std::ofstream outfile(out_path, std::ios::out | std::ios::trunc);
          if (outfile.is_open()) {
              outfile << "输出内容\n";
              outfile.close();
          }
          return 0;
      }
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:32:36