2 qq 37283655 qq_37283655 于 2017.01.09 16:03 提问

c语言把结构体内容写入文件问题

#include
#define m 2
main(){
int i;
FILE *fp;
typedef struct{
int year;
int month;
int day;
}date;
struct student{
int number;

char name[20];
date birth;
}student1[m];
fp=fopen("student.doc","w");
for(i=0;i<m;i++){
student1[i].number=i;
scanf("%s",student1[i].name);
scanf("%d%d%d",&(student1[i].birth.year),&(student1[i].birth.month),&(student1[i].birth.day));
fwrite(&(student1[i]),sizeof(struct student),1,fp);
}
fclose(fp);
}

图片图片

4个回答

qq423399099
qq423399099   Ds   Rxr 2017.01.09 19:22
已采纳

fp = fopen("student.doc", "w");这句不对,写入doc不能用fopen
改成fp = fopen("student.txt", "w");

qq423399099
qq423399099 回复qq_37283655: 你不能直接双击打开,用fread读才行,我写了断读的代码,贴在下面
11 个月之前 回复
qq_37283655
qq_37283655 还是不行 。在文件有字母但没数字字还多了一些[[[[[[[]]]]]]]]
11 个月之前 回复
tangjingyunshiweifen
tangjingyunshiweifen   2017.01.10 09:10

改一下就好了
fp=fopen("student.doc","w");
for(i=0;i<m;i++){
student1[i].number=i;
scanf("%s",student1[i].name);
scanf("%d%d%d",&(student1[i].birth.year),&(student1[i].birth.month),&(student1[i].birth.day));
fwrite(&(student1[i]),sizeof(struct student),1,fp);
}
fclose(fp);

改成

fp=fopen("student.doc","w");
fwrite(&(student1[i]),sizeof(struct student),m,fp);
}
fclose(fp);

qq423399099
qq423399099   Ds   Rxr 2017.01.10 09:31
 #include<stdio.h>
#define m  2
void main(){
    int  i;
    FILE  *fp;
    typedef struct{
        int     year;
        int     month;
        int      day;
    }date;
    struct    student{
        int        number;
        char    name[20];
        date     birth;
    }student1[m];
    fp = fopen("student.txt", "w");
    for (i = 0; i<m; i++){
        student1[i].number = i;
        scanf("%s", student1[i].name);
        scanf("%d%d%d", &(student1[i].birth.year), &(student1[i].birth.month), &(student1[i].birth.day));
        fwrite(&(student1[i]), sizeof(struct student), 1, fp);
    }
    fclose(fp);


    struct student student2[m];
    fp = fopen("student.txt", "r");
    for (i = 0; i<m; i++){
        fread(&(student2[i]), sizeof(struct student), 1, fp);
        printf("%s%d%d%d\n", student2[i].name,(student2[i].birth.year), (student2[i].birth.month), (student2[i].birth.day));

    }
    fclose(fp);

}
qq423399099
qq423399099 回复qq_37283655: 但你双击打开DOC应该看不到你想要的吧
11 个月之前 回复
qq_37283655
qq_37283655 我试过用doc也行的啊,为什么一定要用txt呢?
11 个月之前 回复
qq_37283655
qq_37283655 对的,谢谢!
11 个月之前 回复
dc66584409
dc66584409   2017.01.09 16:23

bzero memset刷新一下,

u011261430
u011261430 回复qq_37283655: memset(void * _Dst,0,size_t _Size);
11 个月之前 回复
qq_37283655
qq_37283655 没用过 memset 能不能具体点
11 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!