簡體   English   中英

fscanf 不返回 EOF 或 fscanf 在 C 中進入無限循環

[英]fscanf not returning EOF or fscanf going to infinite loop in C

我正在嘗試將幾行寫入文件。 寫完行后,當我嘗試使用fscanf從文件中讀取這些行時,它會進入無限循環。 fprintf正在工作,但fscanf將進入無限循環。

#include<stdio.h>
#include<stdlib.h>

  void main()
       {
        FILE *fp;
        int roll;
        char name[25];
        float marks;
        char ch;
        fp = fopen("file.txt","w");           
        if(fp == NULL)
        {
            printf("\nCan't open file or file doesn't exist.");
            exit(0);
        }

        do
        {
             printf("\nEnter Roll : ");
             scanf("%d",&roll);

             printf("\nEnter Name : ");
             scanf("%s",name);
             printf("\nEnter Marks : ");
             scanf("%f",&marks);

             fprintf(fp,"%d%s%f",roll,name,marks);

             printf("\nDo you want to add another data (y/n) : ");
             ch = getche();

             }while(ch=='y' || ch=='Y');

            printf("\nData written successfully...");
              
              
              
            printf("\nData in file...\n");

            while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=EOF)
            printf("\n%d\t%s\t%f",roll,name,marks);
                
              

            fclose(fp);
       }

您已打開文件進行寫入(模式“w”),因此您的scanf調用幾乎肯定會失敗。 即使您修復了模式,也不奇怪:

while((fscanf(fp,"%d%s%f",&roll,name,&marks))!=EOF)

進入無限循環。 如果 stream 中的下一個字符不是 integer 中的有效字符,則scanf將返回零並且不使用它。 它將反復嘗試將該字符讀取為 integer 並反復失敗。 此處正確的方法可能是完全停止使用scanf ,但快速解決方法可能類似於:

int rv;
while( (rv = fscanf(fp,"%d%s%f",&roll,name,&marks)) != EOF ){
    if( rv == 3 ){
        printf(...);
    } else {
        /* probably the right thing to do is break out of
           the loop and emit an error message, but maybe 
           you just want to consume one character to progress
           in the stream. */
        if( fgetc(fp) == EOF ){
            break;
        }
    }
}

編寫while( 3 == fscanf(...))並在錯誤輸入時發出錯誤消息會更常見,但類似上述 kludge 的內容可能有用(取決於您的用例)。

但是您需要修復打開模式。 可能您只想在寫循環之后關閉文件(您當然需要先刷新它才能期望從文件中讀取)並以模式“r”重新打開。

暫無
暫無

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

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