簡體   English   中英

C編程:使用fscanf(),fopen()和格式字符串問題

[英]C Programming : Using fscanf(), fopen(), and format string issue

我有一個名為account.dat的數據文件,其結構如下:

1000:Cash
3000:Common Shares Outstanding
1400:Office Equipment

我正在使用fopen()打開/鏈接文件。 我正在使用fscanf()檢索基於格式字符串的值-“%d:%[^:] \\ n”。 %d代表帳號,':'是分隔符,[^:]是除':'以外的所有字符。

 void getdataf() {
     FILE * infileaccs;
     FILE * infiletrans;
     int acctnumf;
     char acctdesf[DESMAX];

     char filenameacc[40] = "accounts.dat";
     infileaccs = fopen(filenameacc, "r");
     if(infileaccs==NULL){
         printf(" **File \"accounts.dat\" could not be read\n");
         printf(" **Previously entered account titles are not available\n");
         printf(" **Any previously entered transactions will not be used\n");
     } else{
         int i=0;
         while(fscanf(infileaccs, "%d:%[^:]\n",&acctnumf,acctdesf)!= EOF){
             acct[i++]=acctnumf;
             srtaccttyp(acctnumf, i);
             printf("------------>Added unique acct type %d!\n", accttyp[i]);
             printf("------------>element: %d is added into acct array in position acct[%d]\n",acctnumf,i);
             nacct++;
             accttitle(acctdesf);
         }
         fclose(infileaccs);
     } }

但是,此代碼不起作用,只會凍結。 如果您需要更多信息,請提前告訴我。

它似乎停止在while循環中。

您的fscanf格式

while(fscanf(infileaccs, "%d:%[^:]\n",&acctnumf,acctdesf)!= EOF)

掃描第一行中的數字,然后掃描冒號,然后存儲所有字符,直到acctdesf的下一行冒號acctdesf 然后,所有后續fscanf無法將以':'開頭的字符串轉換為int ,從而使您陷入無限循環。

您只想讀到下一行,

int convs;
while((convs = fscanf(infileaccs, "%d:%[^\n]",&acctnumf,acctdesf)) == 2) {
    /* do something */
}
if (convs != EOF) {
    /* oops */
}

因此,對於下一個fscanf從下一行開始的數字仍然存在。

如果沒有與給定格式匹配的數據,則fscanf可以返回0,但是您僅檢查EOF 您應該做的是檢查fscanf的結果,該結果將告訴您已成功掃描了多少個項目,在這種情況下,您要確保fscanf返回的是2或EOF,如果都不返回,則表示存在數據格式化您的輸入中的問題。

暫無
暫無

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

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