C++读写文本文件代码范例解读

开发 后端
C++读写文本文件的操作技巧是在程序编写中比较基础的应用技巧。我们希望初学者可以以本文代码为参考对象,对这一基础知识有一个详尽的了解。

C++编程语言书写方式灵活,可以帮助编程人员轻松的实现各种功能需求。我们在这里以一段代码示例来详细介绍一下C++读写文本文件的实现方法,希望大家可以根据这里介绍的方法充分掌握这一基础应用技巧。

C++读写文本文件代码示例如下:

  1. #include < iostream> 
  2. #include < fstream> 
  3. using namespace std;  
  4. int main()  
  5. {  
  6. const char filename[] = "mytext.txt";  
  7. ofstream o_file;  
  8. ifstream i_file;  
  9. string out_text;  
  10. //写  
  11. o_file.open(filename);  
  12. for (int i = 1; i < = 10; i++)  
  13. {  
  14. o_file < <  "第" < <  i < <  "行"n"; //将内容写入到文本文件中  
  15. }  
  16. o_file.close();  
  17. //读  
  18. i_file.open(filename);  
  19. if (i_file.is_open())  
  20. {  
  21. while (i_file.good())  
  22. {  
  23. i_file >> out_text; //将读取的内容存储到变量out_text中  
  24. cout < <  out_text < <  endl;
     //在控制台输出读取的内容。为什么***一行的内容会出现两次  
  25. }  
  26. }  
  27. else  
  28. cout < <  "打开文件:" < <  filename < <  " 时出错!";  
  29. i_file.close();  
  30. system("PAUSE");  
  31. return 0;  
  1. #include "stdafx.h"  
  2. #include < iostream> 
  3. #include < fstream> 
  4. #include < string> 
  5. using namespace std;  
  6. int _tmain(int argc, _TCHAR* argv[])  
  7. {  
  8. const char filename[]="test.doc";  
  9. ofstream o_file;
    /* 输出流:将数据从内存输出其中ofstream是将数据输出到文件,
    因此对于文件来说是“写”*/  
  10. ifstream i_file;
    /*将数据输入到内存,其中ifstream是说输入的数据在文件中,
    因此对于文件来说是“读”*/  
  11. string out_text;  
  12. //写  
  13. o_file.open(filename);  
  14. for(int i =0;i< =12;i++)  
  15. {  
  16. o_file< < "第"< < i< < "行"n";//将内容写入文本  
  17. }  
  18. o_file.close();  
  19. //读  
  20. i_file.open(filename);  
  21. if(i_file.is_open())  
  22. {  
  23. while(i_file>>out_text)  
  24. {  
  25. cout < <  out_text < <  endl;  
  26. }  
  27. }  
  28. else  
  29. cout< < "打开文件:"< < filename< < "时出错!";  
  30. i_file.close();  
  31. system("PAUSE");  
  32. return 0;  

C++读写文本文件相关操作方法就为大家介绍到这里。

【编辑推荐】

  1. C++初始化列表实现方法详解
  2. C++多态性基本概念讲述
  3. C++获得系统时间具体实现代码解析
  4. 自定函数实现C++读取CSV文件
  5. 讲述C++中调用Python脚本
责任编辑:曹凯 来源: 博客园
相关推荐

2010-01-15 10:05:35

VB.NET文件对象

2009-09-02 19:13:08

C#处理文本文件

2009-08-06 18:33:45

C#处理文本文件

2010-01-15 16:21:45

VB.NET读写文本文

2009-10-29 14:16:32

VB.NET读写文本文

2009-08-26 11:53:56

C#打印文本文件

2009-09-02 19:08:03

C#实现读取文本文件

2009-10-14 10:25:52

VB.NET读写文本文

2010-01-08 16:10:05

VB.NET读写文本文

2009-08-19 17:44:15

C#操作文本文件

2010-04-30 17:38:31

Unix文本

2009-08-20 09:15:20

C#操作文本文件

2009-08-20 10:17:27

C#操作文本文件

2021-11-29 09:46:11

FileReaderJava开发

2009-08-12 17:59:48

C#读取文本文

2009-08-20 09:58:06

C#操作文本文件

2009-09-04 15:56:35

写入文本文件

2015-06-17 14:28:15

Java查询处理方法

2014-03-11 10:11:33

Linux命令more命令文本文件

2009-08-20 09:26:14

C#操作文本文件
点赞
收藏

51CTO技术栈公众号