要创建一个二进制文件,可以使用以下步骤:

  1. 打开一个文件流,指定文件名和打开方式(写入二进制模式)。
#include <fstream>

std::ofstream outfile("example.bin", std::ios::out | std::ios::binary);
  1. 写入数据到文件流中。
char data[] = "Hello, world!";
outfile.write(data, sizeof(data));
  1. 关闭文件流。
outfile.close();

完整的示例代码如下:

#include <fstream>

int main() {
    std::ofstream outfile("example.bin", std::ios::out | std::ios::binary);
    if (!outfile) {
        return 1;
    }

    char data[] = "Hello, world!";
    outfile.write(data, sizeof(data));

    outfile.close();

    return 0;
}

运行此程序后,将在当前目录中创建一个名为“example.bin”的二进制文件,其中包含文本“Hello, world!”

codeblock如何创建一个二进制文件

原文地址: https://www.cveoy.top/t/topic/fFtn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录