author | Markus Bröker <mbroeker@largo.dyndns.tv> |
Fri, 27 Dec 2013 16:00:09 +0100 | |
changeset 167 | 7c6b221900bf |
parent 94 | c100ba6939e3 |
child 169 | df7c720bcaa6 |
permissions | -rw-r--r-- |
90 | 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 (); |
|
94
c100ba6939e3
cppdatabase: removed the useless status message
Markus Bröker <mbroeker@largo.dyndns.tv>
parents:
90
diff
changeset
|
29 |
in.seekg (0, std::ios::beg); |
90 | 30 |
|
31 |
struct Person p; |
|
32 |
||
33 |
while ((in.read ((char *)&p, sizeof (Person))) != NULL) { |
|
34 |
std::cout << p.lastname << ", " << p.firstname << ", " << |
|
35 |
p.position << std::endl; |
|
36 |
} |
|
37 |
} |
|
38 |
||
39 |
using namespace std; |
|
40 |
||
41 |
int main () |
|
42 |
{ |
|
43 |
struct Person p[] = { |
|
44 |
{"Ribery", "Franck", "Midfielder"}, |
|
45 |
{"Lahm", "Phillip", "Defender"}, |
|
46 |
{"Toni", "Luca", "Striker"}, |
|
47 |
{"Klose", "Miroslav", "Striker"}, |
|
48 |
}; |
|
49 |
||
50 |
ifstream in; |
|
51 |
ofstream out; |
|
52 |
||
53 |
out.open (DB_FILE, ios::binary); |
|
54 |
if (!out) { |
|
55 |
cout << "Outputfile Error " << DB_FILE << endl; |
|
56 |
return EXIT_FAILURE; |
|
57 |
} |
|
58 |
||
59 |
for (unsigned int i = 0; i < sizeof (p) / sizeof (Person); i++) { |
|
60 |
make_db_entry (out, p[i]); |
|
61 |
} |
|
62 |
out.close (); |
|
63 |
||
64 |
in.open (DB_FILE); |
|
65 |
if (!in) { |
|
66 |
cout << "Inputfile Error " << DB_FILE << endl; |
|
67 |
return EXIT_FAILURE; |
|
68 |
} |
|
69 |
||
70 |
read_db_entry (in); |
|
71 |
read_db_entry (in); |
|
72 |
||
73 |
in.close (); |
|
74 |
||
75 |
return EXIT_SUCCESS; |
|
76 |
} |