seltkirk
seltkirk

Reputation: 21

It it possible to to read using fscanf till EOF ? C

I'm writing function that reads names,last_names and numbers from txt file and saves them to structure. Variables in the file are arranged in this way

Name | Last Name | Number

My problem is that fscanf have problem with reading last number before EOF.

My code:

int load_phonebook_t(const char *filename, struct entry_t* p, int size)
{
   int a,i,ilosc=0;
   FILE *fp;
   if(filename==NULL || p==NULL || size<1)
   {
      return -1;
   }    
   fp=fopen(filename,"r");
   if(fp==NULL)
   {
      return -2;
   }
   rewind(fp);
   for(i=0;i<size;i++)
   {
      if(i==size-1)
      {
         a=fscanf(fp,"%s | %s | %d[^EOF]",(p+i)->name,(p+i)->last_name,&(p+i)->number);
      }
      else
      {
         a=fscanf(fp,"%s | %s | %d",(p+i)->name,(p+i)->last_name,&(p+i)->number);
      }
      if(a==3)
      {
         ilosc++;
      }
   }
   fclose(fp);
   return ilosc;
}

I tried using fscanf(fp,"%s | %s | %d[^EOF]") but it didn't work. I need an idea how to stop reading before EOF or how to read it correctly.

Edit:

Last few lines from my .txt file:

Annette | Bening | 378422705
George | C.Scott | 209747332
Burt | Lancaster | 568016673
Louis | Gossett Jr. | 528057525

Upvotes: 1

Views: 140

Answers (1)

Joshua
Joshua

Reputation: 43280

Stopping at end of file with scanf is easy.

a=fscanf(fp,"%s | %s | %d",(p+i)->name,(p+i)->last_name,&(p+i)->number);

if (a != 3) {
     /* handle eof; */
     break;
}

There's a lot of stuff yet to do involving malformed files and reading the file once while growing your array, but hey baby steps man. You will reach that eof block on any IO or format error as well.

Upvotes: 0

Related Questions