循序漸進學習讀文件
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 }