【问题标题】:writing binary file in c++ is producing ascii output在 C++ 中编写二进制文件正在产生 ascii 输出
【发布时间】:2021-12-12 08:25:21
【问题描述】:

这可能是一个非常愚蠢的错误,但我很困惑为什么我的代码将指定的数据写为文件中的 ascii 字符而不是二进制格式?我错过了什么?我在网上阅读的大多数教程都遵循这个设置,所以我必须遗漏一些重要的东西。任何帮助表示赞赏。文件中的输出也是“123456”

void MipsInterpret::outFile() {
std::cout << "Writing file" << std::endl;
std::ofstream myFile;
myFile.open(outputFile, std::ios::binary);
if (!myFile) {
    std::cerr << outputFile << " failed to open. Closing " << std::endl;
    exit(1);
}
std::string test = "add $1, $2, $3";

char list[6] = {'1', '2', '3', '4', '5','6'};

myFile.write(list, 6);

if (!myFile.good()) {
    std::cerr << "Error occurred at writing time!" << std::endl;
    exit(1);
}
myFile.close();

}

【问题讨论】:

  • 但是您确实有一个由六个 ASCII 字符组成的数组,那么您希望文件包含什么(在将这些原样写入文件之后)?
  • 我希望二进制文件不可读,所以它会包含一堆十六进制值?除非我的理解不正确
  • '1' 字符被转换为数字0x31,并写入文件。如果您想要实际数字,请使用{ 1,2,3,4,5,6 };,或使用'\x01''\xFF'

标签: c++ io binaryfiles


【解决方案1】:

插入

char list[6] = {'1', '2', '3', '4', '5','6'};

char list[6] = {1, 2, 3, 4, 5, 6};

这将解决问题,因为“1”实际上是二进制的 49

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    相关资源
    最近更新 更多