C++ 创建二进制文件:详细步骤与示例代码
要创建一个二进制文件,可以使用以下步骤:
- 打开一个文件流,指定文件名和打开方式(写入二进制模式)。
#include <fstream>
std::ofstream outfile('example.bin', std::ios::out | std::ios::binary);
- 写入数据到文件流中。
char data[] = 'Hello, world!';
outfile.write(data, sizeof(data));
- 关闭文件流。
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!”。
原文地址: https://www.cveoy.top/t/topic/olkU 著作权归作者所有。请勿转载和采集!