c++ 讀寫文本文件

 1 #include  <iostream>
 2 #include <fstream>    // 讀寫文件的頭文件
 3 #include <string>
 4 using namespace std;  5 /*
 6  1 文本文件 寫文件  7  1 包含頭文件  8  #include <fstream>  9  2 建立流對象  10  ofstream ofs;  11  3 指定路徑和打開方式  12  ofs.open(路徑, 打開方式);  13  打開方式:  14  ios::in 讀文件打開  15  ios::out 寫文件打開  16  ios::ate 從文件尾打開  17  ios::app 追加方式打開  18  ios::trunc 若是已經有文件 先刪除在撞見  19  ios::binary 二進制方式  20  4 寫內容  21  ofs << "寫點數據" << endl;  22  5 關閉文件  23  ofs.close();  24 */
 25 void write() {  26     // 1 包含頭文件 #include <fstream>  27     // 2 建立流對象
 28  ofstream ofs;  29     // 3 指定路徑和打開方式 
 30     ofs.open("text.txt", ios::out);  31     // 4 寫內容
 32     ofs << "寫點數據" << endl;  33     ofs << "寫點數據2" << endl;  34     ofs << "寫點數據3" << endl;  35 
 36     // 5 關閉文件
 37  ofs.close();  38 }  39 
 40 /*
 41 2 文本文件 讀文件  42  1 包含頭文件  43  #include <fstream>  44  2 建立流對象  45  ifstream ifs;  46  3 指定路徑和打開方式  47  ifs.open(路徑, 打開方式);  48  打開方式:  49  ios::in 讀文件打開  50  ios::out 寫文件打開  51  ios::ate 從文件尾打開  52  ios::app 追加方式打開  53  ios::trunc 若是已經有文件 先刪除在撞見  54  ios::binary 二進制方式  55  4 讀取 四種方式  56  ifs << "寫點數據" << endl;  57  5 關閉文件  58  ifs.close();  59 */
 60 
 61 void read() {  62     // 1 頭文件  63     // 2 建立流對象
 64  ifstream ifs;  65     // 3 打開文件 判斷是否打開成功
 66     ifs.open("text.txt", ios::in);  67     if (!ifs.is_open()) {  68         cout << "文件打開失敗!" << endl;  69         return;  70  }  71     // 4 讀數據 四種方式  72     // 第一種方式  73     //char buf[1024] = { 0 };  74     //while (ifs >> buf) {  75     // cout << buf << endl;  76     //}  77     
 78     // 第二種  79     //char buf[1024];  80     //while (ifs.getline(buf, sizeof(buf))) {  81     // cout << buf << endl;  82     //}  83 
 84     // 第三種  85     //string buf;  86     //while (getline(ifs, buf)) {  87     // cout << buf << endl;  88     //}  89 
 90     // 第四種 不推薦用
 91     char c;  92     while ((c=ifs.get()) != EOF) {  93         cout << c;  94  }  95 
 96      
 97     // 5 關閉流
 98  ifs.close();  99 } 100 
101 int main() { 102 
103  read(); 104 
105     system("pause"); 106     return 0; 107 }
相關文章
相關標籤/搜索