I have a data file called accounts.dat that is structured like below:
1000:Cash
3000:Common Shares Outstanding
1400:Office Equipment
I am using fopen() to open/link the file. And I am using fscanf() to retrieve the values based on the format string – “%d:%[^:]\n”. The %d represent the account number, ‘:’ is the deliminator, and [^:] is all chars except ‘:’.
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);
} }
However this code does not work, it just freezes. Please let me know if you need more info, thanks in advance.
It seems to stop at the while loop.
Your
fscanfformatscans the number in the first line, then the colon, and then stores all characters until the colon on the next line in
acctdesf. Then all subsequentfscanfs fail to convert a string beginning with':'to anint, trapping you in an infinite loop.You want to read just up to the next line,
so that the number starting the next line is still there for the next
fscanf.