華束师免大学数学科学学院 School of Mathematical Sciences,East China Normal University 第十五讲 文件流与输出输入重载 http://math.ecnu.edu.cn/~jypan
http://math.ecnu.edu.cn/~jypan 第十五讲 文件流与输出输入重载
输入输出流 在 C++中,所有的输入输出都通过“流”来描述。 D输入流: 数据流向程序(input) 一输出流:数据从程序中流出(output) ·具体实现方法:流类和流对象 口文件流类与文件流对象 口文件流对象与文件关联 口文件读写:文本文件与二进制文件 口重载输出输入运算符<<和>> http://math.ecnu.edu.cn/~jypan 2
http://math.ecnu.edu.cn/~jypan 2 输入输出流 文件流类与文件流对象 文件流对象与文件关联 文件读写:文本文件与二进制文件 重载输出输入运算符 << 和 >> 在 C++ 中,所有的输入输出都通过“流”来描述。 ►输入流:数据流向程序 (input) ►输出流:数据从程序中流出 (output) ►具体实现方法:流类和流对象
C++I/O库中定义的流类 类名 作用 头文件 ios 抽象父类 iostream istream 通用输入流和其他输入流的父类 iostream ostream 通用输出流和其他输出流的父类 iostream 通用输入输出流和其他输入输出流的父类 ifstream 输入文件流类 fstream ofstream 输出文件流类 fstream 输入输出文件流类 ifstream istream ios iostream fstream ostream ofstream http://math.ecnu.edu.cn/~jypan 3
http://math.ecnu.edu.cn/~jypan 类名 作用 头文件 ios 抽象父类 iostream istream ostream iostream 通用输入流和其他输入流的父类 通用输出流和其他输出流的父类 通用输入输出流和其他输入输出流的父类 iostream ifstream ofstream fstream 输入文件流类 输出文件流类 输入输出文件流类 fstream ios istream ostream ifstream ofstream iostream fstream 3 C++ I/O 库中定义的流类
文件流类 口文件流头文件:fstream #include <fstream> 该头文件中定义了三个文件流类 ofstream 向文件写入数据 ifstream 从文件读取数据 fstream 既读又写 http://math.ecnu.edu.cn/-jypan 4
http://math.ecnu.edu.cn/~jypan 文件流头文件:fstream ► 该头文件中定义了三个文件流类 ofstream 向文件写入数据 ifstream 从文件读取数据 fstream 既读又写 #include <fstream> 4 文件流类
创建文件流对象 fstream fstrm; /1创建一个文件流对象,未绑定到任何文件 fstream fstrm(fname); //创建一个文件流,并绑定到文件fname fstream fstrm(fname,mode); //创建文件流的同时指定文件的打开模式 这里的类fstream也可以是ifstream或ofstream ·如果用ifstream.,则对象所关联的文件只能读 ·如果用ofstream.,则对象所关联的文件只能写 http://math.ecnu.edu.cn/~jypan 5
http://math.ecnu.edu.cn/~jypan ► 这里的类 fstream 也可以是 ifstream 或 ofstream ► 如果用 ifstream,则对象所关联的文件只能读 ► 如果用 ofstream,则对象所关联的文件只能写 5 fstream fstrm; // 创建一个文件流对象,未绑定到任何文件 fstream fstrm(fname); // 创建一个文件流,并绑定到文件 fname fstream fstrm(fname, mode); // 创建文件流的同时指定文件的打开模式 创建文件流对象