c++文件输入输出流fstream,对输入>>和输出<<重载

1. fstream 继承自iostream --> 要包含头文件#include<fstream>

2. 建立文件流对象

3. 打开文件夹

4. 测试是否打开成功

5. 进行读写操作

6. 关闭文件

#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

结果:

posted @ 2014-07-17 17:57  bruceyo  阅读(1613)  评论(0编辑  收藏  举报