NO

Author Topic: Trying to read from file into a structure  (Read 2613 times)

David L Morris

  • Guest
Trying to read from file into a structure
« on: September 08, 2010, 07:22:07 AM »
I am trying to populate a structure and use:-

#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define SIZE 3

struct addr{
   char   Acct_No[6];
   char   Last_Name [24];
   char   First_Name [18];
   char   Middle_Initial [1];
   char   Street [30];
   char   City [16];
   char   State [2];
   char   Zip [10];
} List[SIZE];
 etc. etc.. through main() then:

      for (i=0; i<MAX_NUM; i++)
         if (fread(&List,sizeof (struct addr),1,fin)!=1){
            if (feof(fin)) return;
            printf("File read error\n");
      }


The file records are like so:-

     1STOCKDALE               GARY               8406 GOLDENROD DR             OAK PARK        IL60302

The record seems to be stored in the first member of the structure and not parsed into all structure members.
I am used to doing this in the BASIC languages, but want to master C to keep my old mind working.
I would appreciate any guidance.  Do I have to parse the record and strcpy each field into the structure members?




Offline lingo

  • Member
  • *
  • Posts: 27
Re: Trying to read from file into a structure
« Reply #1 on: September 08, 2010, 08:58:18 AM »
Yepp,

you have to iterate thru the array yourself. Try this:

Code: [Select]
fread(&List[i],sizeof (struct addr),1,fin)  
But be carefull: The stop condition (i<MAX_NUM)
may be a problem. Can't see what your intent is here.

HTH
Lingo
« Last Edit: September 08, 2010, 09:00:13 AM by lingo »

David L Morris

  • Guest
Re: Trying to read from file into a structure
« Reply #2 on: September 08, 2010, 09:59:55 AM »
Thanks Lingo.  I do fread(&List,sizeof (struct addr),1,fin).  The file has 5000 records and while I test this part I set MAX_NUM to 3, so I can get the first three records only.  I probably should sit down with a mentor in C, as this part seems more difficult to grasp than the same job in BASIC.  I notice that the List bracket i bracket does not show up in these posts and don't know why?


« Last Edit: September 08, 2010, 11:04:38 AM by David L Morris »