您的位置:首页 > 编程语言 > C语言/C++

C++文件读写对象

2017-12-17 17:10 337 查看
将对象数组对象写入文件,并读取出来,并重新赋值。

#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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息