/* records.c: Illustrates file positioning */

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

#define MAXRECS 10

struct record
{
    char last[16];
    char first[11];
    int age;
};

static char *get_field(char *, char *);

main()
{
    int nrecs;
    char s[81];
    struct record recs[MAXRECS], recbuf;
    FILE *f;

    /* Carefully store records */
    for (
         nrecs = 0;
         nrecs < MAXRECS && get_field("Last",s);
         ++nrecs
        )
    {
        strncpy(recs[nrecs].last,s,15)[15] = '\0';
        get_field("First",s);
        strncpy(recs[nrecs].first,s,10)[10] = '\0';
        get_field("Age",s);
        recs[nrecs].age = atoi(s);
    }

    /* Write records to file */
    if ((f = fopen("recs.dat","w+b")) == NULL)
        return EXIT_FAILURE;
    if (fwrite(recs,sizeof recs[0],nrecs,f) != nrecs)
        return EXIT_FAILURE;

    /* Position at last record */
    fseek(f,(nrecs-1)*sizeof(struct record),SEEK_SET);
    fread(&recbuf,1,sizeof(struct record),f);
    printf("last: %s, first: %s, age: %d\n",
      recbuf.last,recbuf.first,recbuf.age);

    /* Position at first record */
    rewind(f);
    fread(&recbuf,1,sizeof(struct record),f);
    printf("last: %s, first: %s, age: %d\n",
      recbuf.last,recbuf.first,recbuf.age);

    return EXIT_SUCCESS;
}

static char *get_field(char *prompt, char *buf)
{
    /* Prompt for input field */
    fprintf(stderr,"%s: ",prompt);
    return gets(buf);
}
