1. ofstream
之前讲到,ifstream具有将文件从硬盘中读进内存的功能。而ofstream则是执行反操作,它提供了将文件从内存写入磁盘的功能。
std::ofstream 是 C++ 标准库中用于文件输出的类,它提供了向文件写入数据的能力。std::ofstream 属于 <fstream> 头文件中定义的一部分,是继承自 std::ostream 的派生类,专门用于文件操作。使用 std::ofstream 可以以文本或二进制形式写入文件,非常适用于数据持久化、日志记录等场景。
2. 基本API
(1)open()
打开文件:在创建 std::ofstream 对象时可以直接指定文件路径打开文件,或者使用对象的 open 方法后续打开。
默认情况下,打开的是文本写入模式。
(2)close()
关闭文件:在完成文件写操作后,应该使用 close 方法关闭文件。虽然 std::ofstream 的析构函数会自动关闭文件,但显式关闭文件是一个好习惯,尤其是在文件操作可能影响程序逻辑的情况下。
(3)is_open()
检查文件是否打开成功。虽然还有fail()和good()这两个API可以检查文件打开的状态,但还是建议使用is_open()。
(4)write()
一般在写二进制数据到文件情况下用到这个API。原型如下。
(5)运算符<<
一般在写文本数据到文件情况下用到这个API。参考如下。
(6)rdbuf
获取共享缓冲区指针,这个功能用的不是很多,大家了解就可以,后续将提供例程加以说明。
3. 读写文本
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
std::ofstream file("output.txt");
file << "123" << std::endl;
// 关闭文件
file.close();
return 0;
}
4. 读写二进制
#include <iostream>
#include <fstream>
#include <cstring>
int main(int argc, char* argv[])
{
unsigned char* binary_buf = new unsigned char[1024]();
memset(binary_buf, 1, 1024);
std::ofstream file("output.binary", std::ios::out | std::ios::binary);
file.write(reinterpret_cast<char*>(binary_buf), 1024);
// 关闭文件
file.close();
delete[] binary_buf;
binary_buf = NULL;
return 0;
}
5. 缓冲区指针重定向
#include <iostream>
#include <fstream>
#include <cstring>
int main(int argc, char* argv[])
{
std::ofstream file("output.txt");
file << "123" << std::endl;
/** 保存原来的cout缓冲区指针 */
std::streambuf* orig_cout_streambuf = std::cout.rdbuf();
/** 将cout的缓冲区指针设置为文件流的缓冲区指针 */
std::cout.rdbuf(file.rdbuf());
/** 现在,使用cout输出的任何内容都会写入"output.txt"文件(并不会再输出至终端上) */
std::cout << "This will be written to the file instead of the console." << std::endl;
/** 恢复cout原来的缓冲区指针,使输出重回控制台 */
std::cout.rdbuf(orig_cout_streambuf);
// 关闭文件
file.close();
return 0;
}