zoukankan      html  css  js  c++  java
  • 从键盘输入4个学生的有关数据,然后把它们保存到磁盘文件中,最后从磁盘文件中读取数据输出到屏幕

    练习fwrite()和fread()函数的使用 方法。

    fwrite()函数的作用是将一个长度为29字节的数据块送到文件中(一个student_type类型结构体变量的长度为它的成员长度之和,即10+2+2+15=29)

    代码
    #include<stdio.h>
    #define SIZE 2
    #define LEN sizeof(struct student_type)

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

    void save()
    {
    FILE
    *fp;
    int i;
    if((fp=fopen("test","wb"))==NULL)
    {
    printf(
    "无法打开文件\n");
    exit(
    1);
    }
    for(i=0;i<SIZE;i++)
    if(fwrite(&stud[i],LEN,1,fp)!=1)
    printf(
    "文件写入失败。\n");

    fclose(fp);
    }

    void input()
    {
    int i;
    printf(
    "姓名\t学号\t年龄\t地址\n");
    for(i=0;i<SIZE;i++)
    scanf(
    "%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
    }

    void output()
    {
    FILE
    *fp;
    int i;
    if((fp=fopen("test","rb"))==NULL)
    {
    printf(
    "无法打开文件\n");
    exit(
    1);
    }

    for(i=0;i<SIZE;i++)
    {
    fread(
    &stud[i],LEN,1,fp);
    printf(
    "%-10s %4d %4d %-15s\n",stud[i].name,stud[i].num,stud[i].age,stud[i].addr);
    }

    fclose(fp);

    }

    void main()
    {
    input();
    save();
    output();
    }
  • 相关阅读:
    我的黑客偶像
    2020-2021-1学期 学号20201222 《信息安全专业导论》第5周学习总结
    XOR加密
    pep/9
    我的黑客偶像
    学年2020-2021,1 学号:20201222《信息安全专业导论》第4周学习总结”
    IEEE754浮点数转换
    师生关系
    罗马数字转阿拉伯数字
    第三周总结
  • 原文地址:https://www.cnblogs.com/qixin622/p/1673603.html
Copyright © 2011-2022 走看看