C语言-往文件中写读学生数据

来源:互联网 发布:淘宝客服链接网址 编辑:程序博客网 时间:2024/06/07 12:34
#include<stdio.h>#include<stdlib.h>#define N 100struct stu{    long ID;    int score;    char name[N];};int main(){    struct stu *a;    int i,num;    char array[N];    FILE * fp;    if((fp=fopen("demo.txt","w+"))==NULL)    {        printf("file open error\n");        getchar();        exit(1);    }    printf("How many students?\n");    scanf("%d",&num);    printf("\n");    a=(struct stu*)malloc(sizeof(struct stu)*num);    if(a==NULL)    {        printf("malloc error\n");        getchar();        exit(1);    }    for(i=0; i<num; i++)    {        printf("Please input the name score ID of %d\n",i+1);        scanf("%s %d %ld",a[i].name,&(a[i].score),&(a[i].ID));        fprintf(fp,"%s\t%d\t%ld\n",a[i].name,a[i].score,(a[i].ID));    }    rewind(fp);    printf("\n");    printf("The content below has been written:\n");    while(fgets(array,N,fp)!=NULL)    {        printf("%s",array);    }    fclose(fp);    free(a);    return 0;}