C++文件读写对象

来源:互联网 发布:淘宝电工工具袋 编辑:程序博客网 时间:2024/04/30 21:16

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

#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;    }}
原创粉丝点击