tags:

views:

111

answers:

1

How do I put the records from the random access file DATA.data into the array allRecs[10]?

/*Reading a random access file and put records into an array*/
#include <stdio.h>

/*  somestruct structure definition */
struct somestruct{
    char namn[20];
    int artNr;
}; /*end structure somestructure*/

int main (void) {
    int i = 0;
    FILE *file; /* DATA.dat file pointer */
    /* create data with default information */
    struct somestruct rec = {"", 0};
    struct somestruct allRecs[10]; /*here we can store all the records from the file*/
    /* opens the file; exits it file cannot be opened */
    if((file = fopen( "DATA.dat", "rb")) == NULL) {
     printf("File couldn't be opened\n");
    } 
    else { 
     printf("%-16s%-6s\n", "Name", "Number");
     /* read all records from file (until eof) */
     while ( !feof( file) ) { 
      fread(&rec, sizeof(struct somestruct), 1, file);
      /* display record */
      printf("%-16s%-6d\n", rec.namn, rec.artNr);
      allRecs[i].namn = /* HOW TO PUT NAME FOR THIS RECORD IN THE STRUCTARRAY allRecs? */
      allRecs[i].artNr = /* HOW TO PUT NUMBER FOR THIS RECORD IN THE STRUCTARRAY allRecs? */
      i++;
     }/* end while*/
     fclose(file); /* close the file*/
    }/* end else */
    return 0; 
}/* end main */
+1  A: 

Two ways immediately come to mind. First, you can simply assign, like this:

allRecs[i] = rec;

But, judging by your code, you don't even need that - you can simply read directly in the appropriate element:

fread(&allRecs[i], sizeof(struct somestruct), 1, file);
/* display record */
printf("%-16s%-6d\n", allRecs[i].namn, allRecs[i].artNr);
i++;

By the way - are you sure that the file will never contain more than 10 records? Because if it does, you'll get into a lot of trouble this way...

Vilx-
No I'm not sure the how do you make it dynamic?
Chris_45