使用ofstream可实现C++文件写入,包含<fstream>头文件后,通过ofstream创建文本或二进制文件,默认覆盖原内容,添加std::ios::app可追加写入,std::ios::binary用于二进制数据,需用reinterpret_cast转换指针类型,write()函数写入原始数据,操作后应检查is_open()和good()等状态确保成功。

在C++中写入文件,通常使用标准库中的 fstream 头文件提供的功能。通过 ofstream(output file stream)类可以轻松实现文件的写入操作。下面介绍几种常用的文件写入方法。
#include <fstream>
#include <iostream>
#include <string>
std::ofstream file("example.txt");
if (file.is_open()) {
file << "Hello, C++ File Writing!\n";
file << "This is the second line.";
file.close();
} else {
std::cout << "Unable to open file";
}
std::ofstream file("example.txt", std::ios::app);
if (file.is_open()) {
file << "\nAppended line.";}
file.close();
} else {
std::cout << "Failed to open file for appending.";}
}
int data[] = {10, 20, 30, 40};
std::ofstream binFile("data.bin", std::ios::binary);
if (binFile) {
binFile.write(reinterpret_cast<const char*>(data), sizeof(data));
binFile.close();
}
基本上就这些。掌握 ofstream 的基本用法,就能满足大多数C++文件写入需求。关键是记得检查文件是否成功打开,并根据需要选择覆盖或追加模式。二进制写入适用于保存结构体或数组等原始数据。不复杂但容易忽略细节。
以上就是c++++中怎么写入文件_C++文件写入操作方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号