c++ - 在VC环境中,使用fwrite 写入浮点数数据异常
PHP中文网
PHP中文网 2017-04-17 13:54:11
0
3
943
#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中文网

认证0级讲师

全部回覆(3)
PHPzhong

你可以按 F5 調試,在彈框的時候點重試,會跳到發生異常的點,左邊會有個箭頭標出是哪行造成的錯誤。

按這裡提供的信息,至少有一處肯定是錯的:

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

要改成:

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

Windows 下讀寫二進位的文件,開啟方式必須指定 "b" 參數,不然即使不發生執行時期異常,出來的文件資料也不對。

PHPzhong

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

大家讲道理

~~就上面的程式碼來看,你的VC6有問題,你試試換個機器就能測試通過

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!