cppdatabase.cc
changeset 90 d494813f9e5b
child 94 c100ba6939e3
equal deleted inserted replaced
89:66f0244c2863 90:d494813f9e5b
       
     1 /**
       
     2  * cppdatabase.cc
       
     3  * Copyright (C) 2009 Markus Broeker
       
     4  *
       
     5  * stores data in a file and retrieves it back
       
     6  */
       
     7 
       
     8 #include <cstdlib>
       
     9 #include <iostream>
       
    10 #include <fstream>
       
    11 
       
    12 #define DB_FILE "/tmp/test.dat"
       
    13 
       
    14 struct Person {
       
    15     char lastname[80];
       
    16     char firstname[80];
       
    17     char position[80];
       
    18 };
       
    19 
       
    20 void make_db_entry (std::ofstream& out, struct Person& p)
       
    21 {
       
    22     out.write ((char *)&p, sizeof (Person));
       
    23 }
       
    24 
       
    25 void read_db_entry (std::ifstream& in)
       
    26 {
       
    27     std::cout << "clear eof" << std::endl;
       
    28     in.clear ();
       
    29     std::cout << "seek status: " << in.seekg (0, std::ios::beg) <<
       
    30         std::endl << std::endl;
       
    31 
       
    32     struct Person p;
       
    33 
       
    34     while ((in.read ((char *)&p, sizeof (Person))) != NULL) {
       
    35         std::cout << p.lastname << ", " << p.firstname << ", " <<
       
    36             p.position << std::endl;
       
    37     }
       
    38 }
       
    39 
       
    40 using namespace std;
       
    41 
       
    42 int main ()
       
    43 {
       
    44     struct Person p[] = {
       
    45         {"Ribery", "Franck", "Midfielder"},
       
    46         {"Lahm", "Phillip", "Defender"},
       
    47         {"Toni", "Luca", "Striker"},
       
    48         {"Klose", "Miroslav", "Striker"},
       
    49     };
       
    50 
       
    51     ifstream in;
       
    52     ofstream out;
       
    53 
       
    54     out.open (DB_FILE, ios::binary);
       
    55     if (!out) {
       
    56         cout << "Outputfile Error " << DB_FILE << endl;
       
    57         return EXIT_FAILURE;
       
    58     }
       
    59 
       
    60     for (unsigned int i = 0; i < sizeof (p) / sizeof (Person); i++) {
       
    61         make_db_entry (out, p[i]);
       
    62     }
       
    63     out.close ();
       
    64 
       
    65     in.open (DB_FILE);
       
    66     if (!in) {
       
    67         cout << "Inputfile Error " << DB_FILE << endl;
       
    68         return EXIT_FAILURE;
       
    69     }
       
    70 
       
    71     read_db_entry (in);
       
    72     read_db_entry (in);
       
    73 
       
    74     in.close ();
       
    75 
       
    76     return EXIT_SUCCESS;
       
    77 }