1

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.

0

2 Answers 2

1

Your fscanf format

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

scans 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 subsequent fscanfs fail to convert a string beginning with ':' to an int, trapping you in an infinite loop.

You want to read just up to the next line,

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

so that the number starting the next line is still there for the next fscanf.

Sign up to request clarification or add additional context in comments.

Comments

0

fscanf can return 0 if there was no data that matched the given format, but you are only checking for EOF. What you should do is check the result of fscanf which will tell you how many items were successfully scanned, in this case, you want to ensure that fscanf is returning either 2, or EOF, and if it is neither then there was a data formatting issue in your input.

1 Comment

I think their might be something wrong with my format, fscanf is giving me 0. How must I rewrite my format string (%d:%[^:]\n) to match the structured in my accounts.dat file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.