1. 继承关系
basic_ostream<CharT, Traits> 输出流
basic_istream<CharT, Traits> 输入流
basic_iostream<CharT, Traits> 输入输出流
上面的三个类是抽象类,所有的实现都继承自它们三个。
Q1
: 为什么在实际使用中通常使用的是std::ofstream而不是std::basic_ofstream。
answer:
两者表示相同的意思,只是std::ofstream是别名。
/// Class for @c char output file streams.
typedef basic_ofstream ofstream;
Q2
: 模板类有两个模板类型,为什么实际定义中只指定了一个char
answer:
在模板类申明中指定了默认参数。
template<typename _CharT, typename _Traits = char_traits<_CharT> > class basic_ofstream;
2. 具体使用
读文件:
#include <fstream>
#include <iostream>
int main(int argc, char const *argv[])
{
std::string filename = "input.txt";
// std::basic_ifstream<char, std::char_traits<char>> finstream(filename.c_str());
std::ifstream fin;
fin.open(filename, std::ios::in|std::ios::binary);
if (!fin.is_open()){
std::cerr << "Error: Failed to open file " << filename << std::endl;
return 1;
}
std::string str;
// while (finstream >> str)
// {
// std::cout << str << std::endl;
// }
while (std::getline(fin, str))
{
std::cout << str << std::endl;
}
std::cout << "File opened successfully." << std::endl;
fin.close();
return 0;
}
写文件:
#include <iostream>
#include <fstream>
int main(){
// Open a file for writing
std::ofstream outfile;
outfile.open("output.txt", std::ios::out &~std::ios::trunc);
std::cout << std::hex << "std::ios::out "<< static_cast<long>(std::ios::out) << std::endl;
std::cout << std::hex << "std::ios::trunc "<< static_cast<long>(std::ios::trunc) << std::endl;
std::cout << std::hex << "std::ios::out | std::ios::trunc"<< static_cast<long>(std::ios::out | std::ios::trunc) << std::endl;
// Check if the file was opened successfully
if (!outfile.is_open())
{
std::cout << "File failed to open!" << std::endl;
return -1;
}
// write to the file
std::string message = "Hello, world!";
// outfile << message << std::endl;
// outfile.write(message.c_str(), message.size());
outfile.put(message.c_str()[0]);
// close the file
outfile.close();
return 0;
}
- 支持空构造函数,后面调用open函数
- 重写了operator bool()
- openmode组合