介绍
之前总结过C的标准I/O库函数,现在总结一下C++的标准I/O库:iostream, fstream, sstream。
同样,与设备无关也是基于流,即处理对象就是字符流或者二进制流。
一个是格式化I/O,用在上层一点,另一个正好相反。
使用流来进行I/O的流程如下:
- 创建 & 打开流对象
- 将流对象与IO设备连接
- 读 / 写
- 将流对象与IO设备断开
- 关闭 & 销毁流对象
另外,为了支持不同的字符类型,甚至字符集,I/O对象类基本上都使用了C++中的模板类来定义结构。
在头文件iosfwd中对basic_xxx这一系列的模板类进行了实例化并进行了重命名:
iostream - 流IO
ios,即basic_ios<char>,用来保存流对象中一些比较常用的属性。它们的父类ios_base保存独立于模板参数的数据,ios保存依赖于模板参数的数据。
istream, ostream两者分别提供输入和输出的API。
iostream,多重继承自istream和ostream,iostream类定义在<istream>,提供双向的I/O。
streambuf为字符流提供内存buffer,及一些API。
cin / cout / cerr / clog 标准流对象。
标准流对象可以直接进行“3. 读 / 写”。
iomanip - 设置I/O格式
- <iomanip> header: setw(), setprecision(), setbas(), setfill().
- <iostream> header: fixed|scientific, left|right|internal, boolalpha|noboolalpha, etc.
fstream - 文件I/O
继承自iostream。
字符文件&二进制文件的处理方式同一般流。
ifstream, ofstream用于文件输入输出,分别继承自istream,ostream。
filebuf为文件提供内存buffer,及一些API。
sstream - 字符串流
istringstream, ostringstream用于string buffer的输入输出。
stringbuf为string流提供内存buffer,及一些API。
参考
其它C++参考资料
C++ Specifications
- ISO/IEC 14882:2011 "Programming Language. C++" (The "C++11", version 3).
- ISO/IEC 14882:2003 "Programming Language. C++" (The "C++03", version 2).
- ISO/IEC 14882:1998 "Programming Language. C++" (The "C++98", version 1).
C++ Textbooks
- Bjarne Stroustrup (Creator of C++), "The C++ Programming Language", 4th ed, 2012. (Covers C++11.)
- Nicolai M Josuttis, "The C++ Standard Library: A Tutorial and Reference", 2nd ed, 2012.
- Bjarne Stroustrup, "The Design and Evolution of C++".
- Stephen Prata, "C++ Primer Plus Developer's Library", 6th ed, Addison-Wesley, 2012. (Covers C++11.)
- Paul Deitel & Harvey Deitel, "C++ How to Program", 8th ed, Prentice Hall, 2012.
- Stanley B. Lippman, Josee Lajoie, Barbara E Moo "C++ Primer", 5th ed, 2012. (Covers C++11.)
- Scott Meyers, "Effective C++: 55 Specific Ways to Improve your Programs and Design", 3rd ed, 2005; "Effective STL: 50 Specific Ways to Improve your use of the Standard Template Library", 2001.
- Herb Sutter, "Exceptional C++: 47 Engineering Puzzles, Programming Problems and Solutions", 1999; "More Exceptional C++: 40 New Engineering Puzzles, Programming Problems and Solution", 2001.
- Gary J. Bronson, "Program Development and Design using C++".
- Robert C. Seacord, "Secure Coding in C and C++", 2nd ed, 2013.
Online References
- http://www.cplusplus.com (C++ documents, tutorials, and references).
- GNU GCC (GNU Compiler Collection) @ http://gcc.gnu.org, with source codes.
- Bjarne Stroustrup's C++11 FAQ @ http://www.stroustrup.com/C++11FAQ.html.