首页 文章

C编程:使用fscanf(),fopen()和格式字符串问题

提问于
浏览
1

我有一个名为accounts.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循环中 .

2 回答

  • 1

    你的 fscanf 格式

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

    扫描第一行中的数字,然后是冒号,然后存储所有字符,直到 acctdesf 中下一行的冒号 . 然后所有后续的 fscanf 都无法将以 ':' 开头的字符串转换为 int ,将您陷入无限循环 .

    你想读到下一行,

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

    所以下一行开始的数字仍然存在于下一个 fscanf .

  • 0

    如果没有与给定格式匹配的数据, fscanf 可以返回0,但您只检查 EOF . 你应该做的是检查 fscanf 的结果,它会告诉你成功扫描了多少项,在这种情况下,你想确保 fscanf 返回2或EOF,如果它不是,那么就有数据格式化输入中的问题 .

相关问题