使用open()來開啟串流,使用get()或put()來進行輸出入,這比較像是 C語言 的作法,在C++中,可以直接操作串流來進行檔案的輸出入。
不必使用open()來開啟串流,ifstream、ofstream和fstream都有建構函式,可以直接指定檔案並開啟串流,例如: :
ofstream fout("file.txt");
這個程式片段會自動開啟串流,之後就可以利用這個串流直接進行輸出,就像是使用cout一樣,例如:
fout << "Justin" << 28 << endl;
下面這個程式使用串流進行格式化檔案I/O,寫入姓名與成績資料至檔案中,然後再將它讀出:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
char ch;
ofstream fout("temp");
if(!fout) {
cout << "無法寫入檔案\n";
return 1;
}
fout << "Justin" << "\t" << 90 << endl;
fout << "momor" << "\t" << 80 << endl;
fout << "Bush" << "\t" << 75;
fout.close();
ifstream fin("temp");
if(!fin) {
cout << "無法讀入檔案\n";
return 1;
}
char name[80];
int score;
cout << "Name\tScore\n";
while(!fin.eof()) {
fin >> name >> score;
cout << name << "\t" << score << endl;
}
fin.close();
return 0;
}
執行結果:
Name Score
Justin 90
momor 80
Bush 75
Justin 90
momor 80
Bush 75
下面這個程式使用串流讀入使用者的輸入,然後將之寫入指定的檔案中:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
char str[80];
if(argc != 2) {
cout << "指令: write <filename>" <<endl ;
return 1;
}
ofstream fout(argv[1]);
if(!fout) {
cout << "無法寫入檔案" <<endl ;
return 1;
}
do {
cout << "\$ ";
cin >> str;
fout << str << endl;
} while(*str != 'q');
fout.close();
return 0;
}
執行結果:
write temp
\$ 這是一段測試文字
\$ 測試
\$ q
\$ 這是一段測試文字
\$ 測試
\$ q
開啟temp來看,您就可以看到剛才寫入的結果;下面這個程式可以進行文字檔案的複製,並在複製的過程中,將所有的字母轉為大寫:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
if(argc != 3) {
cout << "指令: copy <input> <output>" << endl;
return 1;
}
ifstream fin(argv[1]);
ofstream fout(argv[2]);
if(!fin) {
cout << "無法讀入來源檔案" << endl;
return 1;
}
if(!fout) {
cout << "無法輸出目的檔案" << endl;
fin.close();
return 1;
}
char ch;
fin.unsetf(ios::skipws); // 不忽略空白
while(!fin.eof()) {
fin >> ch;
if(ch >= 97 && ch <= 122)
ch -= 32;
if(!fin.eof())
fout << ch;
}
fin.close();
fout.close();
return 0;
}
執行時指定來源檔案與目的檔案,您可以發現目的檔案的字母全部被轉為大寫了。