// records.cpp: Illustrate file positioning
#include <iostream.h>
#include <fstream.h>
#include <strstream.h>
#include <stddef.h>

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

main()
{
    const size_t BUFSIZ = 81;
    int nrecs = 0;
    char buf[BUFSIZ];
    struct record recbuf;
    int mode = ios::bin | ios::trunc | ios::out | ios::in;
    fstream f("recs.dat",mode);

    for (;;)
    {
        // Prompt for input line
        cout << "Enter LAST,FIRST,AGE: ";
        if (!cin.getline(buf,BUFSIZ))
            break;

        // Extract fields
        istrstream line(buf);
        line.getline((char *)&recbuf.last,sizeof recbuf.last,',');
        line.getline((char *)&recbuf.first,sizeof recbuf.first,',');
        line >> recbuf.age;

        // Write to file
        f.write((char *) &recbuf, sizeof recbuf);
        ++nrecs;
    }

    /* Position at last record */
    f.seekg((nrecs-1)*sizeof(struct record),ios::beg);
    if (f.read((char *) &recbuf,sizeof recbuf))
        cout << "last: " << recbuf.last
             << ", first: " << recbuf.first
             << ", age: " << recbuf.age
             << endl;

    /* Position at first record */
    f.seekg(0,ios::beg);
    if (f.read((char *) &recbuf,sizeof recbuf))
        cout << "last: " << recbuf.last
             << ", first: " << recbuf.first
             << ", age: " << recbuf.age
             << endl;

    return 0;
}

// Sample execution
// Enter LAST,FIRST,AGE: Lincoln,Abraham,188
// Enter LAST,FIRST,AGE: Bach,Johann,267
// Enter LAST,FIRST,AGE: Tze,Lao,3120
// Enter LAST,FIRST,AGE: ^Z
// last: Tze, first: Lao, age: 3120
// last: Lincoln, first: Abraham, age: 188

