GCC 使用的C++库:libstdc++
libstdc++ 源代码包含在 GCC 的源代码中,即 libstdc++-v3 目录中的代码
头文件:<iosfwd>
template<typename _CharT, typename _Traits = char_traits<_CharT> >
class basic_istream;
template<typename _CharT, typename _Traits = char_traits<_CharT> >
class basic_ostream;
template<typename _CharT, typename _Traits = char_traits<_CharT> >
class basic_iostream;
typedef basic_istream<char> istream;
typedef basic_ostream<char> ostream;
typedef basic_iostream<char> iostream;
头文件:<iostream>
对输入输出流的定义:
extern istream cin; /// Linked to standard input
extern ostream cout;/// Linked to standard output
extern ostream cerr;/// Linked to standard error (unbuffered)
extern ostream clog;/// Linked to standard error (buffered)
//extern 说明定义代码在 cpp 文件中
// For construction of filebuffers for cout, cin, cerr, clog
// ios_base::Init 类负责初始化输入输出流
static ios_base::Init __ioinit;
代码文件:<globals_io.cc>
在这里定义了足够大的内存:
typedef char fake_istream[sizeof(istream)];
typedef char fake_ostream[sizeof(ostream)];
fake_istream cin;
fake_ostream cout;
fake_ostream cerr;
fake_ostream clog;
typedef char fake_stdiobuf[sizeof(stdio_sync_filebuf<char>)];
fake_stdiobuf buf_cout_sync;
fake_stdiobuf buf_cin_sync;
fake_stdiobuf buf_cerr_sync;
typedef char fake_filebuf[sizeof(stdio_filebuf<char>)];
fake_filebuf buf_cout;
fake_filebuf buf_cin;
fake_filebuf buf_cerr;
代码文件:<ios_init.cc>
这里完成输入输出流的初始化:
ios_base::Init::Init()
{
new (&buf_cout_sync) stdio_sync_filebuf<char>(stdout);
new (&buf_cin_sync) stdio_sync_filebuf<char>(stdin);
new (&buf_cerr_sync) stdio_sync_filebuf<char>(stderr);
// The standard streams are constructed once only and never destroyed.
new (&cout) ostream(&buf_cout_sync);
new (&cin) istream(&buf_cin_sync);
new (&cerr) ostream(&buf_cerr_sync);
new (&clog) ostream(&buf_cerr_sync);
cin.tie(&cout);
cerr.setf(ios_base::unitbuf);
cerr.tie(&cout);
}
ios_base::Init::~Init()
{
cout.flush();
cerr.flush();
clog.flush();
}
//该函数负责改变输入输出的工作方式
bool ios_base::sync_with_stdio(bool sync)
{
new (&buf_cout) stdio_filebuf<char>(stdout, ios_base::out);
new (&buf_cin) stdio_filebuf<char>(stdin, ios_base::in);
new (&buf_cerr) stdio_filebuf<char>(stderr, ios_base::out);
cout.rdbuf(&buf_cout);
cin.rdbuf(&buf_cin);
cerr.rdbuf(&buf_cerr);
clog.rdbuf(&buf_cerr);
}
输入输出流的两种工作方式:
1、普通的工作方式,头文件:<stdio_sync_filebuf.h>
template<typename CharT, typename Traits = std::char_traits<CharT> > class stdio_sync_filebuf : public std::basic_streambuf<CharT, Traits>
2、和 fstream 一样的工作方式,头文件:<stdio_filebuf.h>
template<typename CharT, typename _Traits = std::char_traits<CharT> >
class stdio_filebuf : public std::basic_filebuf<CharT, Traits>
fstream 的流用到了一个本地化facet:codecvt,用于字符的转换
输入输出流的实际工作代码在 streambuf 以及子类中
streambuf 有如下 protected 虚函数:
本地化函数: imbue
Buffer management and positioning: setbuf、seekoff、seekpos、sync
输入函数 (get): showmanyc、xsgetn、underflow、uflow、pbackfail
输出函数 (put): xsputn、overflow