首页 > 在VC环境中,使用fwrite 写入浮点数数据异常

在VC环境中,使用fwrite 写入浮点数数据异常

#include<stdio.h>
#define SIZE 1
typedef struct
{
    float num;
    float age;
 }student;
 
student stu[SIZE];
 
void save()
{
    FILE *fp;
    int i;
    if((fp=fopen("dat.txt","w"))==NULL)
    {
        printf("无法打开此文件!\n");
        return;
    }
    for(i=0;i<SIZE;i++)
    if(fwrite(&stu[i], sizeof(student), 1, fp) != 1)
    printf("文件写入错误。!\n");
    fclose(fp);
}
 
void main()
{
    int i;
    for(i=0;i<SIZE;i++)
        scanf("%f%f",&stu[i].num,&stu[i].age);
    save();
}


~~就上面的代码来看,你的VC6有问题,你试试换个机器就能测试通过


if(fwrite(&stu[i], sizeof(student), 1, fp) != 1)
应为
if(fwrite(stu[i], sizeof(student), 1, fp) != 1)


你可以按 F5 调试,在弹框的时候点重试,会跳到发生异常的点,左边会有个箭头标出是哪行造成的错误。

按这里提供的信息,至少有一处肯定是错的:

    if((fp=fopen("dat.txt","w"))==NULL)

要改成:

    if((fp=fopen("dat.txt","wb"))==NULL)

Windows 下读写二进制的文件,打开方式必须指定 "b" 参数,不然即使不发生运行时异常,出来的文件数据也不对。

【热门文章】
【热门文章】