c++的文件流包含在<fstream>與<iostream>
其中頭文件中fstream包含三種數據類型,
ofstream 輸出文件流,用於創建文件並且向文件中寫入數據
ifstream 輸入文件流,用於從文件中讀取數據
fstream 文件流,有讀寫功能,即是以上兩個的綜合
ios::in |
打開文件用於讀取。 |
ios::out |
打開文件用於寫入。 |
ios::ate |
文件打開后定位到文件末尾。 |
ios::app |
追加模式。所有寫入都追加到文件末尾。 |
ios::binary |
二進制方式 |
ios::trunc |
如果文件已存在則先刪除該文件 |
一.先介紹幾個函數
1.cin.getline( 參數1 , 參數2 , 參數3 ) ;
參數1 是即將要寫入的對象,參數2 是寫入的最大長度,參數3是結束字符。
參數2和參數3可缺省。
與getline要區分開,cin.getline服務的是char類型,屬於istream流,而getline服務的對象是string類型,是屬於string流,兩者是不一樣的函數。
getline(參數1,cin) // 參數1 是要寫入的對象。
2.cin.ignore() //函數會忽略掉之前讀語句所多余的字符。
二.代碼實現
1. 寫入文件,可用ofstream / fstream
a. 先聲明一個ofstream類型
// ofstream out;
b. 將該類型與文件名掛鈎
// out.open("地址+文件名",參數);
//此處參數可多選也可缺省,多選情況例如:out.open(“文件”,in | trunc)
c. 正式寫入文件
//string str;
//getline1(cin,str); //讀取一行
//out<<str; // 將變量str的內容寫入文本中
d. Close關閉
//out.close(); //關閉與文件聯系
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 int main(){ 6 //可將聲明與文件聯系合在一起: ofstream out("data.txt"); 7 ofstream out; 8 out.open("data.txt"); 9 string str; 10 getline(cin,str); 11 out<<str; 12 return 0; 13 }
問題:如何面對多行存儲。 在windows中: /r/n才是換行,即:out<<str<<"/r/n";
方案1:
1 ofstream out; 2 out.open("data.txt"); 3 string str; 4 getline(cin,str); 5 out<<str<<endl; 6 7 getline(cin,str); 8 out<<str<<endl;
方案2:(好像\n也可)
1 ofstream out; 2 out.open("data.txt"); 3 string str; 4 getline(cin,str); 5 out<<str<<"\r\n"; 6 7 getline(cin,str); 8 out<<str<<"\r\n";
2. 讀取文件,可用ifstream
a) 先聲明一個ifstream類型
b) Ifstream類型與文件名掛鈎
c) 正式讀取
d) 關閉
讀法1:單個讀取
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 int main(){ 6 7 string str; 8 9 ifstream in; 10 11 in.open("baby.txt"); 12 in>>str; 13 cout<<str<<endl; 14 15 in>>str; 16 cout<<str<<endl; 17 18 return 0; 19 }
輸出結果:
顯然這種讀法只能單個讀取(即:遇見空格 或 換行 結束讀入)
讀法2:整行讀取(使用getline函數)
1 #include<iostream> 2 #include<fstream> 3 #include<string> 4 using namespace std; 5 int main(){ 6 7 string str; 8 9 ifstream in; 10 11 in.open("baby.txt"); 12 13 getline(in,str); 14 cout<<str<<endl; 15 16 getline(in,str); 17 cout<<str<<endl; 18 19 return 0; 20 }
運行結果:
如果遇見漢字亂碼問題,則是文件編碼與系統編碼不同而導致的,詳情看下鏈接。
https://blog.csdn.net/Jinxiaoyu886/article/details/101350354