// Collection of code snippets by Arne VajhÃ¸j 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <cstring>

using namespace std;

const int MAX_NAME = 50;
const int MAX_ADDRESS = 50;

struct person
{
    char name[MAX_NAME];
    char address[MAX_ADDRESS];
    bool active;
};

void write(fstream& f, person data, int recno)
{
    f.seekg(recno * sizeof(person));
    f.write((char *)&data, sizeof(person));
}

bool read(fstream& f, person& data, int recno)
{
    return f.seekg(recno * sizeof(person)) && f.read((char *)&data, sizeof(person));
}

void create()
{
    fstream f("file2.dat", ios::binary | ios::out);
    person p1;
    strcpy(p1.name, "Anders Andersen");
    strcpy(p1.address, "A vej 1");
    p1.active = true;
    write(f, p1, 0);
    person p2;
    strcpy(p2.name, "Børge Børgesen");
    strcpy(p2.address, "B vej 2");
    p2.active = true;
    write(f, p2, 1);
    f.close();
}

void show()
{
    fstream f("file2.dat", ios::binary | ios::in);
    int recno = 0;
    person data;
    while(read(f, data, recno))
    {
        if(data.active)
        {
            cout << data.name << " : " << data.address << endl;
        }
        recno++;
    }
    f.close();
}

void modify()
{
    fstream f("file2.dat", ios::binary | ios::in | ios::out);
    person p;
    strcpy(p.name, "Carl Carlsen");
    strcpy(p.address, "C vej 3");
    p.active = true;
    write(f, p, 2);
    person del;
    read(f, del, 1);
    del.active = false;
    write(f, del, 1);
    f.close();
}

int main()
{
    create();
    show();
    modify();
    show();
    return EXIT_SUCCESS;
}
