首页 > 编程 > C++ > 正文

C++文件读写代码分享

2020-05-23 14:18:59
字体:大 中 小
来源:转载
供稿:网友

本文给大家分享的是2个C++实现文件读写的代码,都非常的简单实用,有需要的小伙伴可以参考下。

编写一个程序,统计data.txt文件的行数,并将所有行前加上行号后写到data1.txt文件中。

算法提示:

行与行之间以回车符分隔,而getline()函数以回车符作为终止符。因此,可以采用getline()函数读取每一行,再用一个变量i计算行数。

(1)实现源代码

 

 
  1. #include <iostream> 
  2. #include <fstream> 
  3. #include <string> 
  4. #include <sstream> 
  5.  
  6. using namespace std; 
  7.  
  8. int coutFile(char * filename,char * outfilename) 
  9. { 
  10. ifstream filein; 
  11. filein.open(filename,ios_base::in); 
  12. ofstream fileout; 
  13. fileout.open(outfilename,ios_base::out); 
  14. string strtemp; 
  15. int count=0; 
  16. while(getline(filein,strtemp)) 
  17. { 
  18. count++; 
  19. cout<<strtemp<<endl; 
  20. fileout<<count<<" "<<strtemp<<endl; 
  21. } 
  22. filein.close(); 
  23. fileout.close(); 
  24. return count; 
  25. } 
  26.  
  27.  
  28. void main() 
  29. { 
  30. cout<<coutFile("c://data.txt","c://data1.txt")<<endl; 
  31. } 

再来一个示例:

下面的C++代码将用户输入的信息写入到afile.dat,然后再通过程序读取出来输出到屏幕

 

 
  1. #include <fstream> 
  2. #include <iostream> 
  3. using namespace std; 
  4.  
  5. int main () 
  6. { 
  7.  
  8. char data[100]; 
  9.  
  10. // open a file in write mode. 
  11. ofstream outfile; 
  12. outfile.open("afile.dat"); 
  13.  
  14. cout << "Writing to the file" << endl; 
  15. cout << "Enter your name: "; 
  16. cin.getline(data, 100); 
  17.  
  18. // write inputted data into the file. 
  19. outfile << data << endl; 
  20.  
  21. cout << "Enter your age: "; 
  22. cin >> data; 
  23. cin.ignore(); 
  24.  
  25. // again write inputted data into the file. 
  26. outfile << data << endl; 
  27.  
  28. // close the opened file. 
  29. outfile.close(); 
  30.  
  31. // open a file in read mode. 
  32. ifstream infile; 
  33. infile.open("afile.dat"); 
  34.  
  35. cout << "Reading from the file" << endl; 
  36. infile >> data; 
  37.  
  38. // write the data at the screen. 
  39. cout << data << endl; 
  40.  
  41. // again read the data from the file and display it. 
  42. infile >> data; 
  43. cout << data << endl; 
  44.  
  45. // close the opened file. 
  46. infile.close(); 
  47.  
  48. return 0; 
  49. } 

程序编译执行后输出如下结果

 

 
  1. $./a.out 
  2. Writing to the file 
  3. Enter your name: Zara 
  4. Enter your age: 9 
  5. Reading from the file 
  6. Zara 
  7. 9 

以上所述就是本文的全部内容了,希望大家能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表