簡體   English   中英

如何使用fread從文件中讀取特定數據?

[英]How to read particular data from file using fread?

以下代碼使用fwrite將學生的數據寫入文件,並使用fread讀取數據:

 struct record
{
    char name[20];
    int roll;
    float marks;
}student;

#include<stdio.h>
void main()
{
        int i;
        FILE *fp;
        fp=fopen("1.txt","wb");      //opening file in wb to write into file

        if(fp==NULL)    //check if can be open
        {
            printf("\nERROR IN OPENING FILE");
            exit(1);
        }     

        for(i=0;i<2;i++)                        
        {
            printf("ENTER NAME, ROLL_ NO AND MARKS OF STUDENT\n");
            scanf("%s %d %f",student.name,&student.roll,&student.marks);
            fwrite(&student,sizeof(student),1,fp);      //writing into file
         }
        fclose(fp);


        fp=fopen("1.txt","rb");    //opening file in rb mode to read particular data

        if(fp==NULL)     //check if file can be open
        {
            printf("\nERROR IN OPENING FILE");
            exit(1);
        } 

        while(fread(&student.marks,sizeof(student.marks),1,fp)==1)    //using return value of fread to repeat loop   
                    printf("\nMARKS: %f",student.marks);

        fclose(fp);


}

**以上程序的輸出**

如您在輸出圖像中看到的,還將打印具有其他一些值的標記,而對於所需的輸出標記,僅需具有值91和94

為了獲得所需的輸出,需要在上面的代碼中進行哪些更正?

鑒於您是如何對sizeof(student)個字節數執行fwrite操作的,因此一次執行sizeof(student.marks)個字節數的fread操作可能會給您帶來虛假的結果。

考慮這一點的另一種方法是假裝您是圖書發行商。 您一次將書打印或寫在一張紙上。 如果您想返回並在每頁上找到頁碼,則一次不會讀取一個單詞。 那會給你一個奇怪/錯誤的答案。 您閱讀了整個頁面以獲取所需的頁碼。

在每次迭代中研究fread -ing sizeof(student)字節數,並將這些字節寫入student結構中。 然后訪問該結構的marks屬性。

您正在讀取和寫入不同長度的記錄,因此讀取將為您提供空的浮點數。 如果將記錄寫為結構的三個部分,則必須讀回結構的整個長度以找到您感興趣的字段。

while(fread(&student, sizeof(student), 1, fp) == 1))    //using return value of fread to repeat loop   
                    printf("\nMARKS: %f",student.marks);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM