定义于头文件 <fstream>
template< class CharT, |
类模板 basic_ofstream
实现文件上基于流的高层输出操作。它将 std::basic_ostream 的高层接口赋予基于文件的流缓冲( std::basic_filebuf )。
std::basic_ofstream
典型实现只保有一个非导出成员: std::basic_filebuf<CharT, Traits> 的实例。
亦对常用字符类型定义二个特化:
类型 | 定义 |
ofstream | basic_ofstream<char> |
wofstream | basic_ofstream<wchar_t> |
文件操作
关闭关联文件
std::basic_ofstream<CharT,Traits>::close
void close(); |
关闭关联文件。
等效地调用 rdbuf()->close() 。若操作期间出现错误,则调用 setstate(failbit) 。
参数
(无)
返回值
(无)
注意
此函数为 basic_ofstream 的析构函数在流对象离开作用域时调用,通常不直接调用。
调用示例
#include <fstream>
#include <utility>
#include <string>
#include <iostream>int main()
{std::ofstream ofstream1("test1.txt", std::ios::in);std::ofstream ofstream2("test2.txt", std::ios::in);std::ofstream ofstream3("test3.txt", std::ios::in);std::cout << "ofstream1 is: " << (ofstream1.is_open() ? "true" : "false") << std::endl;std::cout << "ofstream2 is: " << (ofstream2.is_open() ? "true" : "false") << std::endl;std::cout << "ofstream3 is: " << (ofstream3.is_open() ? "true" : "false") << std::endl;std::cout << std::endl;std::cout << "std::ofstream close" << std::endl;ofstream1.close();ofstream2.close();ofstream3.close();std::cout << std::endl;std::cout << "ofstream1 is: "<< (ofstream1.is_open() ? "true" : "false") << std::endl;std::cout << "ofstream2 is: "<< (ofstream2.is_open() ? "true" : "false") << std::endl;std::cout << "ofstream3 is: "<< (ofstream3.is_open() ? "true" : "false") << std::endl;std::cout << std::endl;return 0;
}
输出
非成员函数
特化 std::swap 算法
std::swap(std::basic_ofstream)
template< class CharT, class Traits > |
为 std::basic_ofstream 特化 std::swap 算法。交换 lhs
与 rhs
的状态。等效地调用 lhs.swap(rhs) 。
参数
lhs, rhs | - | 要交换状态的流 |
返回值
(无)
异常
(无)
调用示例
#include <fstream>
#include <utility>
#include <string>
#include <iostream>int main()
{std::ofstream ofstream1("test1.txt", std::ios::out);std::cout << "ofstream1 is: "<< (ofstream1 ? "true" : "false") << std::endl;std::ofstream ofstream2("test2.txt", std::ios::out);std::cout << "ofstream2 is: "<< (ofstream2 ? "true" : "false") << std::endl;std::cout << std::endl;ofstream1 << "hello 1" << " ";ofstream2 << "hello 2" << " ";//为 std::basic_ofstream 特化 std::swap 算法。//交换 lhs 与 rhs 的状态。等效地调用 lhs.swap(rhs) 。std::cout << "std::swap(ofstream1, ofstream2) " << std::endl;std::swap(ofstream1, ofstream2);ofstream1 << "hello 1" << " ";ofstream2 << "hello 2" << " ";ofstream1.close();ofstream2.close();std::cout << std::endl;std::ifstream ifstream1("test1.txt", std::ios::in);std::cout << "ifstream1 is: "<< (ifstream1.is_open() ? "true" : "false") << std::endl;if (ifstream1.is_open()){std::cout << ifstream1.rdbuf() << std::endl;}std::cout << std::endl;std::ifstream ifstream2("test2.txt", std::ios::in);std::cout << "ifstream2 is: "<< (ifstream2.is_open() ? "true" : "false") << std::endl;if (ifstream2.is_open()){std::cout << ifstream2.rdbuf() << std::endl;}std::cout << std::endl;return 0;
}
输出