码迷,mamicode.com
首页 > 编程语言 > 详细

fread和fwrite对结构体数组从文件读入或写入

时间:2015-03-31 09:11:23      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

从键盘输入4个学生数据,把他们转存到磁盘文件中去
重点内容

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

#define SIZE 2
struct student_type
{
    char name[10];
    int num;
    int age;
    char addr[15];
}stud[SIZE];


main()
{
    void display();
    void save();
    printf("%s\n","liuwei");
    int i;
    for (i = 0; i<SIZE; i++)
        scanf("%s%d%d%s", stud[i].name, &stud[i].num,
        &stud[i].age, stud[i].addr);
    save();
    display();
}


void save()
{
    FILE *fp;
    int  i;
    if ((fp = fopen("d:\\stu_dat.data", "wb")) == NULL)
    {
        printf("cannot open file\n");
        return;
    }
    for (i = 0; i<SIZE; i++)
    if (fwrite(&stud[i], sizeof(struct student_type), 1, fp) != 1)
        printf("file write error\n");
    fclose(fp);
}

void display()
{
    FILE *fp;
    int  i;
    if ((fp = fopen("d:\\stu_dat.data", "rb")) == NULL)
    {
        printf("cannot open file\n");
        return;
    }
    for (i = 0; i<SIZE; i++)
    {
        fread(&stud[i], sizeof(struct student_type), 1, fp);
        printf("%s",stud[i].name);
        printf("%-10s %4d %4d %-15s\n", stud[i].name,
            stud[i].num, stud[i].age, stud[i].addr);
    }

    fclose(fp);
}


----------

fread和fwrite对结构体数组从文件读入或写入

标签:

原文地址:http://blog.csdn.net/liuweidagege/article/details/44757839

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!