- #include <stdio.h>
- #include <string.h>
- struct student {
- char name[21];
- int age;
- float score;
- };
- int main(int argc, const char * argv[]) {
- struct student stu1[3]={{"李白",28,59.5f},{"杜甫",33,78.4f},{"王勃",18,98.3f}};
- FILE *fp = fopen("stu.data", "wb+");
-
-
- if (fp != NULL) {
-
- for (int i=0; i<3; i++) {
- fwrite(&stu1[i], sizeof(struct student), 1, fp);
- }
- }
- printf("写入成功\n");
- rewind(fp);
- struct student stu2 [3];
- for (int i=0; i<3; i++) {
- fread(&stu2[i], sizeof(struct student), 1, fp);
- }
- for (int i=0; i<3; i++) {
- printf("姓名:%s 年龄:%d 成绩:%.2f\n",stu2[i].name,stu2[i].age,stu2[i].score);
- }
-
-
- fclose(fp);
- }
复制代码
|
|