需要包括庫文件
#include <fstream>
(1) ofstream:寫操作,輸出文件類滴须;
(2) ifstream:讀操作舌狗,輸入文件類;
(3) fstream:可同時讀寫的文件類扔水。
一般使用ofstream 和ifstream更加清楚明了
ifstream fin("input.txt");
ofstream fout("input.txt");
if (! fin.is_open()) { cout << "Error opening file"; exit (1); } //判斷是否open成功
f (! out.is_open()) { cout << "Error opening file"; exit (1); } //判斷是否open成功
“>>” 從文件讀入數(shù)據(jù)痛侍, “<<”數(shù)據(jù)寫入文件
使用getline 讀入一行數(shù)據(jù)到字符數(shù)組:
char buffer[256];
while (fin.getline (buffer,256) )
{ //或者! fin.eof()
cout << buffer << endl;
}
使用geline讀入一行數(shù)據(jù)到字符串:
string s;
while( getline(fin,s) ){
cout << "Read from file: " << s << endl;
}
使用>>逐詞讀取魔市,按空格區(qū)分
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();
}