cunit9输入输出流.ppt

  1. 1、本文档共75页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 9.4.2  文本文件的读写 int main(){ inventory car1("夏利2000","805637928",156,80000,105000),car2; inventory motor1("金城125",,302,10000,13000),motor2; ofstream distfile("d:\\Ex9_9.data"); distfile<<car1<<motor1; //注意ofstream是ostream的派生类 distfile.close(); cout<<car1; cout<<motor1; cout<<car2; cout<<motor2; ifstream sourfile("d:\\Ex9_9.data"); //这样分两次打开,可避免读文件时,误改了源文件 sourfile>>car2>>motor2; sourfile.close(); cout<<car2; cout<<motor2; return 0; } 9.4.3  二进制文件的读写 【例9.10】创建二进制数据文件,及数据文件的读取。 类inventory与【例9.9】基本一样,只是用二进制文件的Bdatatofile()和Bdatafromfile()取代了文本文件的提取运算符>>和插入运算符<<。 void inventory::Bdatafromfile(ifstream&sour){ char k[20]; sour.read(k,20); Description=k; sour.read(k,10); No=k; sour.read((char*)&Quantity,sizeof(int)); sour.read((char*)&Cost,sizeof(double)); sour.read((char*)&Retail,sizeof(double)); } //由此可见读和写是完全对称的过程,次序决不能错 9.4.3  二进制文件的读写 void inventory::Bdatatofile(ofstream&dist){ dist.write(Description.c_str(),20); //由string类的c_str()函数转为char* dist.write(No.c_str(),10); dist.write((char*)&Quantity,sizeof(int)); dist.write((char*)&Cost,sizeof(double)); dist.write((char*)&Retail,sizeof(double));} int main(){ inventory car1("夏利2000","805637928",156,80000,105000),car2; inventory motor1("金城125",,302,10000,13000),motor2; ofstream ddatafile("d:\\Ex9_10.data",ios::out|ios::binary); car1.Bdatatofile(ddatafile); motor1.Bdatatofile(ddatafile); cout<<"对象car1:"<<endl; cout<<car1; cout<<"对象motor1:"<<endl; cout<<motor1; cout<<"对象car2:"<<endl; cout<<car2; cout<<"对象motor2:"<<endl; cout<<motor2; 9.4.3  二进制文件的读写 ddatafile.close(); ifstream sdatafile("d:\\Ex9_10.data",ios::in|ios::binary); //重新打开文件,从头读取数据 car2.Bdatafromfile(sdatafile); //从文件读取数据复制到对象car2 if(sdatafile.eof()==0) cout<<"读文件成功"<<endl;

文档评论(0)

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

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

1亿VIP精品文档

相关文档