c++文件輸入輸出流fstream,對輸入>>和輸出<<重載

1. fstream 繼承自iostream --> 要包含頭文件#include<fstream>ios

2. 創建文件流對象ide

3. 打開文件夾函數

4. 測試是否打開成功測試

5. 進行讀寫操做spa

6. 關閉文件code

#include<iostream>
#include<fstream>

using namespace std;

int main(){
    ifstream ifile;
    ofstream ofile;
    
    ifile.open("d:\\fileIn.txt");
    ofile.open("d:\\fileOut.txt");

    if (ifile.fail() || ofile.fail()){
        cerr << "open file fail\n";
        return EXIT_FAILURE;
    }

    char ch;
    ch = ifile.get();
    cout << ch << endl;
    while (!ifile.eof()){
        ofile.put(ch);
        ch = ifile.get();
    }

    ifile.close();
    ofile.close();

    int i;
    cin >> i;
    return 0;
}
View Code

輸入三個學生的姓名,學好,年齡和住址,並存入文件中,再從文件中讀出來:對象

 1 #include<iostream>
 2 #include<fstream>
 3 using namespace std;
 4 
 5 class student{
 6 public: 
 7     char name[10];
 8     int num;
 9     int age;
10     char addr[20];
11     friend ostream & operator<<(ostream &out, student &s);
12     friend istream & operator>>(istream &in, student &s);
13 };
14 ostream & operator<<(ostream &out, student &s){
15     out << s.name << " " << s.num << " " << s.age << " " << s.addr << endl;
16     return out;
17 }
18 istream & operator>>(istream &in, student &s){
19     in >> s.name >> s.num  >> s.age >> s.addr;
20     return in;
21 }
22 int main(){
23     ifstream ifile;
24     ofstream ofile;
25     ofile.open("d:\\s.txt");
26 
27     student s;
28     for (int i = 1; i <= 3; i++){
29         cout << "請輸入第" << i << "個學生的姓名 學號 年齡 地址" << endl;
30         cin >> s;   //調用>>運算符重載函數,輸入學生信息
31         ofile << s; //調用<<運算符重載函數,將學生信息寫入到文件中
32     }
33     ofile.close();
34 
35     cout << "\n讀出文件內容" << endl;
36     ifile.open("d:\\s.txt");
37     ifile >> s;
38     while (!ifile.eof()){
39         cout << s;
40         ifile >> s;
41     }
42     ifile.close();
43     int i;
44     cin >> i;
45     return 0;
46 }
View Code

結果:blog

相關文章
相關標籤/搜索