C++语言设计(清华大学郑莉)11说课.ppt

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
* * * * 打开文件的方法(一)举例 #includefstream using namespace std; void fn() { ofstream myf(mydata); if(myf.fail()) { cerrerror\n; return; } myf.....; } 例:ifstream myinf(“abc.dat”,ios::nocreate); 例:fstream myinout(“abc.dat”,ios::in|ios::out); * 打开文件的方法(二) 首先建立一个对象,在需要时再由open()函数将流对象和一个具体的文件相连 ifstream::open(char*,int=ios::in,int=filebuf::openprot) ofstream::open(char*,int=ios::out,int=filebuf::openprot) fstream::open(char*,int,int=filebuf::openprot) e.g. ofstream output; output.open(“output.dat”) * 文件关闭 void ifstream::close() void ofstream::close() void fstream::close() e.g. output.close(); * 文本文件的使用 对文本文件读写方法与标准输入/输出流cin,cout的使用方法相同。 例:将源文件拷贝到目的文件 * 文本文件使用例1 #includeiostream.h #includefstream.h #includestdlib.h void main() { char filename1[256],filename2[256]; cout“input source name:”; cinfilename1; cout“input target name:”; cinfilename2; ifstream infile(filename1); ofstream outfile(filename2); * 文本文件使用例1(续) if(!infile) { cout“can’t open”filename1“\n”; exit(1); } //判断文件1是否打开成功 if(!outfile) { cout“can’t open”filename2“\n”; exit(1); } //判断文件2是否打开成功 char ch; while(infile.get(ch)) outfile.put(ch); infile.close(); outfile.close(); } * 文本文件使用例2 设文本文件data.txt中有若干实数,每个实数之间用空格或换行符隔开,求出文件中的这些实数的平均值。 #includeiostream.h #includefstream.h #includestdlib.h void main() { float sum=0,temp; int count=0; * 文本文件使用例2(续) ifstream infile(“data.txt”); if(!infile) { cout“can’t open data.txt”“\n”; exit(1);    } while(infiletemp) { sum+=temp; count++; } cout“result:”sum/count“”\n; infile.close(); } * 二进制文件使用 对二进制文件的读写操作 istream istream::read(char*,int); 将由第二个参数所指定的字节数读到由第一个参数所指定的字符型指针所指向的存储单元中。 ostream ostream::write(char*,int); 第二个参数指定的写入的字节数,第一个参数指定要写到文件中的字节串的起始地址。 * 文件读二进制记录 #include iostream #include fstream #include cstring using namespace

文档评论(0)

4477769 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档