我有一个名为 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 循环。
最佳答案
你的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
仍然存在。
关于C 编程 : Using fscanf(), fopen() 和格式字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676025/