C++文件读写对象

将对象数组对象写入文件,并读取出来,并重新赋值。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <stdio.h>
#include<cmath>
using namespace std;
struct STU
{
    int sn;
    char name[20];
    int score;
} students;
void main()
{
    STU students[6]/* = { 1,"lihua", 100, 2, "wufang", 99, 3, "liu", 98 }*/;
    students[0].sn = 1;
    strcpy(students[0].name, "lihua");
    students[0].score = 100;
    students[1].sn = 2;
    strcpy(students[1].name, "wufang");
    students[1].score = 99;
    students[2].sn = 3;
    strcpy(students[2].name, "liu");
    students[2].score = 98;
    FILE *fp,*fp1;
    fp = fopen("C:\\Users\\yihong\\Desktop\\a.txt","wb");
    for (int i = 0; i < 3; i++) {
        fwrite(&students[i], sizeof(students[i]), 1, fp);
    }
    fclose(fp);
    fp1 = fopen("C:\\Users\\yihong\\Desktop\\a.txt", "rb");
    STU studentsread;
    for (int i = 0; i < 3; i++) {
        fread(&students[i+3], sizeof(students[i]), 1, fp1);
    }
    fclose(fp);
    for (int i = 3; i < 6; i++)
    {
        cout << students[i].sn << "    " << students[i].name << "    " << students[i].score << endl;
    }
}
  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值