cppdatabase.cc
changeset 90 d494813f9e5b
child 94 c100ba6939e3
new file mode 100644
--- /dev/null
+++ b/cppdatabase.cc
@@ -0,0 +1,77 @@
+/**
+ * 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 ();
+    std::cout << "seek status: " << in.seekg (0, std::ios::beg) <<
+        std::endl << std::endl;
+
+    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;
+}