Debian Codegraph @

yo/iostreams/examples/readwrite.cc

raw
1 #include <iostream>
2 #include <fstream>
3 #include <string>
4 #include <climits>
5 using namespace std;
6
7 void err(char const *msg)
8 {
9 cout << msg << '\n';
10 }
11
12 void err(char const *msg, long value)
13 {
14 cout << msg << value << '\n';
15 }
16
17 void read(fstream &index, fstream &strings)
18 {
19 int idx;
20
21 if (!(cin >> idx)) // read index
22 {
23 cin.clear(); // allow reading again
24 cin.ignore(INT_MAX, '\n'); // skip the line
25 return err("line number expected");
26 }
27
28 index.seekg(idx * sizeof(long)); // go to index-offset
29
30 long offset;
31
32 if
33 (
34 !index.read // read the line-offset
35 (
36 reinterpret_cast<char *>(&offset),
37 sizeof(long)
38 )
39 )
40 return err("no offset for line", idx);
41
42 if (!strings.seekg(offset)) // go to the line's offset
43 return err("can't get string offset ", offset);
44
45 string line;
46
47 if (!getline(strings, line)) // read the line
48 return err("no line at ", offset);
49
50 cout << "Got line: " << line << '\n'; // show the line
51 }
52
53 void write(fstream &index, fstream &strings)
54 {
55 string line;
56
57 if (!getline(cin, line)) // read the line
58 return err("line missing");
59
60 strings.seekp(0, ios::end); // to strings
61 index.seekp(0, ios::end); // to index
62
63 long offset = strings.tellp();
64
65 if
66 (
67 !index.write // write the offset to index
68 (
69 reinterpret_cast<char *>(&offset),
70 sizeof(long)
71 )
72 )
73 return err("Writing failed to index: ", offset);
74
75 if (!(strings << line << '\n')) // write the line itself
76 return err("Writing to `strings' failed");
77 // confirm writing the line
78 cout << "Write at offset " << offset << " line: " << line << '\n';
79 }
80
81 int main()
82 {
83 fstream index("index", ios::trunc | ios::in | ios::out);
84 fstream strings("strings", ios::trunc | ios::in | ios::out);
85
86 cout << "enter `r <number>' to read line <number> or "
87 "w <line>' to write a line\n"
88 "or enter `q' to quit.\n";
89
90 while (true)
91 {
92 cout << "r <nr>, w <line>, q ? "; // show prompt
93
94 index.clear();
95 strings.clear();
96
97 string cmd;
98 cin >> cmd; // read cmd
99
100 if (cmd == "q") // process the cmd.
101 return 0;
102
103 if (cmd == "r")
104 read(index, strings);
105 else if (cmd == "w")
106 write(index, strings);
107 else if (cin.eof())
108 {
109 cout << "\n"
110 "Unexpected end-of-file\n";
111 return 1;
112 }
113 else
114 cout << "Unknown command: " << cmd << '\n';
115 }
116 }