zoukankan      html  css  js  c++  java
  • 《用二进制方式向文件读写一组数据》


    /*
    用二进制方式向文件读写一组数据
    一般的调用方式为:
    fread(buffer,size,count,fp);
    fwrite(buffer,size,count,fp);
    其中:
    buffer:是一个地址,对fread来说,它是用来存放从文件读入的数据的存储区的地址。
    对fwrite来说,是要把此地址开始的存储区中的数据向文件输出(以上指的是起始地址)
    size:要读写的字节数
    count:要读写多少个数据项(每个数据项的长度为size)
    fp:FILE类型指针

    从键盘输入10个学生的有关数据,然后把他们转存到磁盘上去
    */

    #include<stdio.h>
    #include<stdlib.h>
    #define SIZE 3
    struct Student_type
    {
    char name[10];
    int num;
    int age;
    char addr[30];
    }stu[SIZE]; //定义全局结构体数组stu,包含10个学生的数据

    void save()
    {
    FILE *fp;
    int i;
    if((fp=fopen("f:\FILE_1\file_5.txt","wb"))==NULL)
    {
    printf("can't open file ");
    exit(0);
    //return;
    }
    for(i=0;i<SIZE;i++)
    {
    if(fwrite(&stu[i],sizeof(struct Student_type),1,fp)!=1)
    //fputs(" ",fp);
    printf("file write error! ");
    }
    fclose(fp);

    }

    void print()
    {
    FILE *fp;
    int i;
    if((fp=fopen("f:\FILE_1\file_5.txt","rb"))==NULL)
    {
    printf("can't open file! ");
    exit(0);
    }
    for(i=0;i<SIZE;i++)
    {
    fread(&stu[i],sizeof(struct Student_type),1,fp);
    printf("%-10s%4d%4d%-25s ",stu[i].name,stu[i].num,stu[i].age,stu[i].addr);
    }
    fclose(fp);

    }

    int main()
    {
    int i;
    printf("Please enter data of students: ");
    for(i=0;i<SIZE;i++)
    scanf("%s%d%d%s",stu[i].name,&stu[i].num,&stu[i].age,stu[i].addr);
    save();
    print();
    return 0;
    }

  • 相关阅读:
    ZOJ-3230-Solving the Problems
    zoj-3410-Layton's Escape
    cin输入超过文本末尾
    sizeof('a')
    WPF TranslatePoint/TransformToVisual 总返回零
    Lock-free multi-threading
    c++0X 用字符串调用函数
    Vim 的c++语法补齐
    Reentrancy VS Thread safe
    内存屏障
  • 原文地址:https://www.cnblogs.com/sun-/p/4811479.html
Copyright © 2011-2022 走看看