史萊姆論壇

史萊姆論壇 (http://forum.slime.com.tw/)
-   程式語言討論區 (http://forum.slime.com.tw/f76.html)
-   -   [C語言]fread函式讀取Binary檔無法停止? (http://forum.slime.com.tw/thread163633.html)

龍雲 2005-12-17 03:17 PM

[C語言]fread函式讀取Binary檔無法停止?
 
[使用工具]Microsoft Visual Studio .NET 2003
又有問題要麻煩各位前輩嚕

題目要求:讀取Binary檔中的資料再拿來做其他功能[功能就不麻煩各位]
問題點:目前卡在fread[只能用fread]函數讀取檔案時無法停止,會讀到不知哪邊去最後掛
網路查資料是用EOF沒錯呀@@"
希望各位可以解惑,謝謝

附上原始資料檔[txt檔]跟Binary檔[bin檔]
程式碼:
語法:

#include <stdio.h>

#define MAX 100
#define NL 25
#define IL 80

typedef struct
{
        char name[NL];
        int speed;
        double wing,length;
        char introduce[IL],mc;
}dataread;

void main()
{
        dataread data[MAX];
        FILE *inp;
        char state;
        int i=0;

        inp=fopen("input.bin","rb");
       
        do
        {
                i++;
                state=fread(&data[i],sizeof(data),1,inp);
                printf("%s %d %lf %lf %c %s\n",data[i].name,data[i].speed,data[i].wing,data[i].length,data[i].mc,data[i].introduce);       
        }while(state!=EOF);
        fclose(inp);
}

推敲到現在,我覺得我Binary轉檔時可能也是錯誤原因之ㄧ,所以也附上轉檔的程式碼
程式碼:
語法:

#include <stdio.h>
#include <string.h>

#define NL 25
#define IL 80

typedef struct
{
        char name[NL];
        int speed;
        double wing,length;
        char introduce[IL],mc;
}dataread;

void main()
{
        dataread data;
        FILE *inp,*outp;
        char *state;
        int i=0;

        data.wing=0.0;
        data.length=0.0;

        inp=fopen("input.txt","r");
        outp=fopen("input.bin","wb");
       
        for(state=fgets(data.name,NL,inp);
                state!=0;
                state=fgets(data.name,NL,inp))
        {
                if(strlen(data.name)==1)
                        fgets(data.name,NL,inp);
                if(data.name[strlen(data.name)-1]=='\n')
                        data.name[strlen(data.name)-1]='\0';
                fscanf(inp,"%d %lf %lf %c\n",&data.speed,&data.wing,&data.length,&data.mc);
                for(i=0;i<IL;i++)
                        data.introduce[i]='\0';
                state=fgets(data.introduce,IL,inp);
                if(data.introduce[strlen(data.introduce)-1]=='\n')
                        data.introduce[strlen(data.introduce)-1]='\0';
                fwrite(&data,sizeof(data),1,outp);       
        }
        printf("已經轉換完成\n");
        fclose(inp);
        fclose(outp);
}


mini 2005-12-17 10:02 PM

do
{

}while(state!=EOF);
請改成
while(!feof(inp)){

}

您誤解了 size_t fread(void *ptr, size_t size, size_t n, FILE #stream)
其傳回值是告知讀取的資料數目
萬一發生錯誤或已經讀取到檔案底部
則傳回0 或是小於n (第三參數) 的數值

龍雲 2005-12-17 11:49 PM

原來如此,多謝大大的教學與回覆 :ddrf567h:


所有時間均為台北時間。現在的時間是 01:17 PM

Powered by vBulletin® 版本 3.6.8
版權所有 ©2000 - 2024, Jelsoft Enterprises Ltd.

『服務條款』

* 有問題不知道該怎麼解決嗎?請聯絡本站的系統管理員 *


SEO by vBSEO 3.6.1