Home  >  Q&A  >  body text

c++ - 在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();
}

PHP中文网PHP中文网2713 days ago939

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 13:56:11

    You can press F5 to debug and click Retry when the pop-up box pops up. It will jump to the point where the exception occurs. There will be an arrow on the left to mark which line caused the error.

    According to the information provided here, at least one thing is definitely wrong:

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

    should be changed to:

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

    To read and write binary files under Windows, the opening method must specify the "b" parameter. Otherwise, even if no runtime exception occurs, the file data that comes out will be incorrect.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:56:11

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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:56:11

    ~~ Judging from the above code, there is a problem with your VC6. You can try changing the machine and the test will pass

    reply
    0
  • Cancelreply