设为首页 加入收藏

TOP

2.3.7 文件类型(2)
2013-10-07 15:16:25 来源: 作者: 【 】 浏览:64
Tags:2.3.7 文件 类型

2.3.7   文件类型(2)

运行结果如图2.6所示。

 
图2.6   运行结果

试一试:根据以上程序,使用ifstream数据类型定义一个变量,用于读取qq.txt文件中的数据。

上述实例在声明数据流时,分别声明了ifstream和ofstream两种方向的数据流。除了这种方法外,还可以声明一种数据流fstream,fstream在打开文件时,通过参数openmode指定打开方式,openmode参数值如表2.6所示。

表2.6   openmode参数值表

 

【例2.7】 使用fstream数据流来读写文件,程序代码如下。(实例位置:光盘\mr\example\第2章\2.7)

代码位置:光盘\mr\example\第2章\2.7\fstream\fstream.cpp

  1. 01   #include "iostream.h"  
  2. 02   #include "fstream.h"  
  3. 03   #include "iomanip"  
  4. 04   int main()  
  5. 05   {  
  6. 06      fstream infile;   
  7. 07      fstream outfile;  
  8. 08      char name[20];  
  9. 09      char str[30];  
  10. 10      cout<<"请输入文件:"<<"\n";  
  11. 11      cin>>name;  
  12. 12      outfile.open(name,ios::out | ios::trunc);  
  13. 13      if(!outfile)  
  14. 14      {  
  15. 15         cout<<"写文件打开失败!";  
  16. 16         exit(1);  
  17. 17      }  
  18. 18      cout<<"请输入要写入文件的数据:"<<"\n";  
  19. 19      cin>>str;  
  20. 20      outfile<<str;  
  21. 21      outfile.close();  
  22. 22      infile.open(name,ios::in);  
  23. 23      if(!infile)  
  24. 24      {  
  25. 25         cout<<"读文件打开失败!";  
  26. 26         exit(1);  
  27. 27      }  
  28. 28      char c;  
  29. 29      cout<<"输出文件中数据:"<<"\n";  
  30. 30      while(infile.get(c))  
  31. 31      {  
  32. 32         cout<<c;  
  33. 33      }  
  34. 34      cout<<"\n";  
  35. 35      infile.close();  
  36. 36      outfile.open(name,ios::out | ios::app);  
  37. 37      if(!outfile)  
  38. 38      {  
  39. 39         cout<<"写文件打开失败!";  
  40. 40         exit(1);  
  41. 41      }  
  42. 42      cout<<"输入要在文件末尾添加数据:"<<"\n";  
  43. 43      cin>>str;  
  44. 44      outfile<<str;  
  45. 45      outfile.close();  
  46. 46      infile.open(name,ios::in);  
  47. 47      if(!infile)  
  48. 48      {  
  49. 49         cout<<"读文件打开失败!";  
  50. 50         exit(1);  
  51. 51      }  
  52. 52      cout<<"输出文件中数据:"<<"\n";  
  53. 53      while(infile.get(c))  
  54. 54      {  
  55. 55         cout<<c;  
  56. 56      }  
  57. 57      cout<<"\n";  
  58. 58      infile.close();  
  59. 59   } 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.3.7 文件类型(3) 下一篇2.3.7 文件类型(1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: