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

结果:

转载于:https://www.cnblogs.com/bruceyo/p/3851684.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值