1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Record {
int a, b;
string s;
Record(int a, int b, string s) : a(a), b(b), s(s) {}
Record() : a(), b() {}
};
bool output(Record vehicle) {
string plateNumber("12345");
ofstream out(plateNumber, ios::binary);
if (!out)
return false;
out.write(reinterpret_cast<char*>(&vehicle.a), sizeof(int));
out.write(reinterpret_cast<char*>(&vehicle.b), sizeof(int));
// Write the size of the string.
int size = vehicle.s.size();
out.write(reinterpret_cast<char*>(&size), sizeof(int));
// Write the string data.
const char *p = vehicle.s.data();
size_t size2 = vehicle.s.size();
out.write(p, size2);
return true;
}
bool input(Record &vehicle) {
string plateNumber("12345");
ifstream in(plateNumber, ios::binary);
if (!in)
return false;
in.read(reinterpret_cast<char*>(&vehicle.a), sizeof(int));
in.read(reinterpret_cast<char*>(&vehicle.b), sizeof(int));
// Read in the size of the string.
int size = 0;
in.read(reinterpret_cast<char*>(&size), sizeof(int));
// Read in the string.
char str[1000];
in.read(str, size);
vehicle.s = str;
return true;
}
int main() {
Record v(1, 2, "hello");
if (!output(v)) {
cerr << "Error writing file.\n";
return 1;
}
Record w;
if (!input(w)) {
cerr << "Error reading file.\n";
return 1;
}
cout << w.a << ", " << w.b << ", " << w.s << '\n';
return 0;
}
|