标题:fwrite写入数据地址对不上
取消只看楼主
domore
Rank: 1
等 级:新手上路
帖 子:26
专家分:0
注 册:2019-7-25
结帖率:60%
 问题点数:0 回复次数:2 
fwrite写入数据地址对不上
#include<stdio.h>
#include<stdio.h>        
#define SIZE 10
struct Student_type        //定义全局结构体变组stud,包含10个学生数据
    {
    char name[10];
    int num;
    int age;
    char addr[15];
    }stud[SIZE];
FILE *fp;
void save()    //定义save函数,向文件输出SIZE个学生的数据
    {
    //FILE *fp;原来是在这一行的,为了在main函数中也能输出fp,我把它声明为了全局变量
    int i;
    if((fp=fopen("stu.dat","wb"))==NULL)
        {
        printf("can not open file\n");
        return ;
        }
    printf("before:\nfp addr:%d, stud addr:%d,\nsize of a member:%d\n",fp,stud,sizeof(struct Student_type));    //我自己加的
    for(i=0;i<SIZE;i++)
        if(fwrite(&stud[i],sizeof(struct Student_type),1,fp)!=1)
            printf("file write error");
            return ;
    fclose(fp);
    }
int main()
    {
    int i;
    printf("please enter data of students:\n");
    for(i=0;i<SIZE;i++)
        scanf("%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
    save();
    printf("now:\nfp addr:%d, stud addr:%d,\nsize of a member:%d\n",fp,stud,sizeof(struct Student_type));        //我自己加的
    return 0;
    }

[此贴子已经被作者于2019-7-30 06:10编辑过]

搜索更多相关主题的帖子: SIZE struct int addr printf 
2019-07-30 04:22
domore
Rank: 1
等 级:新手上路
帖 子:26
专家分:0
注 册:2019-7-25
得分:0 
对不上是指地址不等,我输出了fp和stud的地址,是不等的,而实际上应该是相等的
#include<stdio.h>
#define SIZE 10
struct Student_type
    {
    char name[10];
    int num;
    int age;
    char addr[15];
    }stud[SIZE];
void save()
    {
    FILE *fp;
    int i;
    if((fp=fopen("stu.dat","wb"))==NULL)
        {
        printf("can not 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");
            return ;
    fclose(fp);
    }
int main()
    {
    int i;
    printf("please enter data of students:\n");
    for(i=0;i<SIZE;i++)
        scanf("%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);
    save();
    return 0;
    }
2019-07-30 05:58
domore
Rank: 1
等 级:新手上路
帖 子:26
专家分:0
注 册:2019-7-25
得分:0 
用我贴子里的代码  
我重新上传了  
2019-07-30 06:12



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-496100-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015721 second(s), 9 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved