C文件的输入输出概要1
第7章 文件的输入输出 第7章 文件的输入输出 基本概念 文件可以保存程序运行的结果 文件使程序操作大量数据成为可能 大型系统的运行需要文件支持 文件是一组相关联的数据的集合 C++将文件看成有序的字节流 基本概念 文件 普通文件 二进制文件 文本文件 输入输出设备:键盘、显示器、打印机等 C++采用相同的方式操作普通文件和I/O设备 基本概念 几个特殊的流对象 标准输出流对象cout 标准输入流对象cin 非缓冲标准错误流对象cerr 缓冲标准错误流对象clog 和文件流相关的几个类 类ifstream——文件的输入 类ofstream——文件的输出 类fstream——文件的输入输出 上述三个类都在头文件fstream.h中 7.1 文件的打开与关闭 ofstream outFile(outFile.txt,ios::out); 可以改写为: ofstream outFile; outFile.open(outFile.txt,ios::out); 或 ofstream outFile; outFile.open(outFile.txt); 文件可以显式关闭: outFile.close(); 例:创建一个输出文件流,并输出一串字符 #includefstream.h void main() { //声明文件流对象 ofstream outFile(outFile.txt,ios::out); if (!outFile) //使用错误流对象输出错误信息 cerrOpen file or create file error.endl; else //输出数据到与对象outFile 关联的文件中 outFile This is a test file.; } 为适应用户习惯,也提供open和close函数完成上述操作 #includefstream.h void main() { //声明文件流对象 ofstream outFile; outFile.open (outFile.txt,ios::out); if (!outFile) //使用错误流对象输出错误信息 cerrOpen file or create file error.endl; else {//输出数据到与对象outFile 关联的文件中 outFile This is a test file.; outFile.close (); } } 7.2 使用插入与提取运算符对磁盘文件进行读写 #includefstream.h void main() {//往文本文件写数据 ofstream outfile1(myfile1.txt); outfile1Hello!...CHINA ANSHANendl; outfile1.close (); //追加数据 outfile1.open (myfile1.txt,ios::app); int x=1212,y=6868; outfile1x yendl; outfile1.close (); //从文本文件读数据并显示在屏幕上 char str1[80],str2[80]; int x2,y2; ifstream infile1(myfile1.txt); infile1str1str2; infile1x2y2; infile1.close (); coutstr1=str1endl; coutstr2=str2endl; coutx2=x2endl; couty2=y2endl; } 7.3 使用类成员函数对磁盘文件进行读写 输入一个字符串写入文件中并统计字符的个数 #includefstream.h void main() { char str[80]; coutInput string :endl; cin.getline (str,80,\n); ofstream fout(ft.txt); int i=0; while(str[i]) fout.put (str[i++]); coutlen=iendl; fout.close (); } 从文件中读出所写字符串并统计字符的个数 void main() { ifstream fin(ft.txt); char ch; i
您可能关注的文档
- bugfree的详细安装与使用概要1.pptx
- BusinessObjects XI 管理(公司内部资料)概要1.ppt
- Business_appointment_商务会谈概要1.ppt
- But what`s a dictionary for? 课概要1.pptx
- Butterknife用法概要1.doc
- But you didn’t概要1.pptx
- Business Etiquette(商务礼仪2014)概要1.pptx
- BWDSP汇编入门概要1.pptx
- buzz marketing概要1.ppt
- byron she walks in beauty 美与媚概要1.ppt
- 2025年全国演出经纪人员资格认定考试试卷带答案(研优卷).docx
- 2025年全国演出经纪人员资格认定考试试卷完整版.docx
- 2025年全国演出经纪人员资格认定考试试题库及完整答案.docx
- 2025年全国演出经纪人员资格认定考试试卷完美版.docx
- 2025年全国演出经纪人员资格认定考试试卷含答案(实用).docx
- 2025年全国演出经纪人员资格认定考试试卷及答案(各地真题).docx
- 2025年下半年内江市部分事业单位公开考试招聘工作人员(240人)备考题库附答案.docx
- 2025年全国演出经纪人员资格认定考试试卷及答案1套.docx
- 2025年下半年四川成都市郫都区面向社会引进公共类事业单位人员2人备考题库最新.docx
- 2025年下半年内江市部分事业单位公开考试招聘工作人员(240人)备考题库附答案.docx
原创力文档

文档评论(0)