須要包括庫文件數組
#include <fstream>spa
(1) ofstream:寫操做,輸出文件類;字符串
(2) ifstream:讀操做,輸入文件類;get
(3) fstream:可同時讀寫的文件類。input
通常使用ofstream 和ifstream更加清楚明瞭string
ifstream fin("input.txt"); it
ofstream fout("input.txt"); class
if (! fin.is_open()) { cout << "Error opening file"; exit (1); } //判斷是否open成功stream
f (! out.is_open()) { cout << "Error opening file"; exit (1); } //判斷是否open成功file
「>>」 從文件讀入數據, 「<<」數據寫入文件
使用getline 讀入一行數據到字符數組:
char buffer[256];
while (fin.getline (buffer,256) ) { //或者! fin.eof()
cout << buffer << endl;
}
、、、、、、、、、、、、、、、、、、、、
使用geline讀入一行數據到字符串:
string s;
while( getline(fin,s) ){
cout << "Read from file: " << s << endl;
}
、、、、、、、、、、、、、、、、、、、、
使用>>逐詞讀取,按空格區分
string s;
while( fin >> s ) {
cout << "Read from file: " << s << endl;
}
、、、、、、、、、、、、、、、、、、、、
使用get()讀取一個字符
char c;
while(!fin.eof()){
c = fin.get()
cout<<c<<endl;
}
、、、、、、、、、、、、、、、、、、、、
使用<<寫文件
if (fout.is_open()) {
fout<< "This is a line.\n";
fout<< "This is another line.\n";
fout.close();
}