cppdatabase.cc
author Markus Bröker <mbroeker@largo.dyndns.tv>
Tue, 01 Jun 2010 23:40:56 +0200
changeset 130 f4b424b93e45
parent 94 c100ba6939e3
child 169 df7c720bcaa6
permissions -rw-r--r--
getbits added committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * cppdatabase.cc
 * Copyright (C) 2009 Markus Broeker
 *
 * stores data in a file and retrieves it back
 */

#include <cstdlib>
#include <iostream>
#include <fstream>

#define DB_FILE "/tmp/test.dat"

struct Person {
    char lastname[80];
    char firstname[80];
    char position[80];
};

void make_db_entry (std::ofstream& out, struct Person& p)
{
    out.write ((char *)&p, sizeof (Person));
}

void read_db_entry (std::ifstream& in)
{
    std::cout << "clear eof" << std::endl;
    in.clear ();
    in.seekg (0, std::ios::beg);

    struct Person p;

    while ((in.read ((char *)&p, sizeof (Person))) != NULL) {
        std::cout << p.lastname << ", " << p.firstname << ", " <<
            p.position << std::endl;
    }
}

using namespace std;

int main ()
{
    struct Person p[] = {
        {"Ribery", "Franck", "Midfielder"},
        {"Lahm", "Phillip", "Defender"},
        {"Toni", "Luca", "Striker"},
        {"Klose", "Miroslav", "Striker"},
    };

    ifstream in;
    ofstream out;

    out.open (DB_FILE, ios::binary);
    if (!out) {
        cout << "Outputfile Error " << DB_FILE << endl;
        return EXIT_FAILURE;
    }

    for (unsigned int i = 0; i < sizeof (p) / sizeof (Person); i++) {
        make_db_entry (out, p[i]);
    }
    out.close ();

    in.open (DB_FILE);
    if (!in) {
        cout << "Inputfile Error " << DB_FILE << endl;
        return EXIT_FAILURE;
    }

    read_db_entry (in);
    read_db_entry (in);

    in.close ();

    return EXIT_SUCCESS;
}