C++ 读取txt文本内容,并将结果保存到新文本

循序渐进学习读文件

 1 // readFile.cpp : 定义控制台应用程序的入口点。
 2 
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <fstream>
 7 #include <string>
 8 using namespace std;
 9 
10 //引申:文件拷贝
11 void fileCopy(string file1,string file2){
12     ifstream in(file1);
13     ofstream out(file2);
14     if(in){
15         string line;
16         while(getline(in,line)){
17             cout << line << endl;
18             out << line << endl;
19         }
20     }
21     else{
22         cout << "File Not Exist" << endl;
23     }
24     in.close();
25     out.close();
26 }
27 int _tmain(int argc, _TCHAR* argv[])
28 {
29     //1.逐行读取TXT文档
30     //ifstream in("E:\workspace\CPP\readFile\config.txt");    
31     //string line;
32     //while(getline(in,line)){//逐行读取in中的数据,并把数据保存在line中
33     //    cout << line << endl;
34     //}
35     //in.close();
36 
37     //2.读取一个文件,并将文件内容写入到另一个文件中
38     //string filePath = "E:\workspace\CPP\readFile\";//文件路径,此处为绝对路径
39     //ifstream in(filePath + "config.txt");    
40     //ofstream out(filePath + "result.txt");
41     //string line;
42     //if(in){
43     //    while(getline(in,line)){
44     //        cout << line << endl;
45     //        out << line << endl;//把从config文件中读取的内容写到result文件中
46     //    }
47     //}
48     //else{
49     //    cout << "File Not Exist" << endl;
50     //}
51     //in.close();
52     //out.close();
53     
54     //3.调用fileCopy方法
55     string filePath = "E:\workspace\CPP\readFile\";
56     string file1 = filePath + "config.txt";
57     string file2 = filePath + "result.txt";
58     fileCopy(file1,file2);
59     
60     return 0;
61 }
原文地址:https://www.cnblogs.com/wanglin2016/p/5648388.html