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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
|
#include <Windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class hw
{
protected:
int id;
string name;
public:
hw();
void SetID(int);
void SetName(string);
int GetID();
string GetName();
};
hw::hw()
{
id = 0;
name = "NULL";
}
void hw::SetID(int i)
{
id = i;
}
void hw::SetName(string str)
{
name = str;
}
int hw::GetID()
{
return id;
}
string hw::GetName()
{
return name;
}
int main()
{
hw HW;
int i;
string str;
int sel;
bool go = 1;
fstream file("hardware.dat", ios::in | ios::out | ios::app | ios::binary);
if (!file.is_open())
{
cout << "can't open file ...." << endl;
system("pause");
return 0;
}
file.seekg(0, file.end);
streamoff a = file.tellg();
if (a == 0)
{
for (int j = 0; j < 100; j++)
file.write(reinterpret_cast<char*>(&HW), sizeof(hw));
file.flush();
}
while (go)
{
system("cls");
cout << "1 -> write\n2 -> read\nselection -> ";
cin >> sel;
cin.sync();
file.sync();
switch (sel)
{
case 1:
{
cout << "Id: ";
cin >> i;
cin.sync();
cout << "name: ";
getline(cin, str);
HW.SetID(i);
HW.SetName(str);
streampos pos = HW.GetID()*sizeof(hw);
file.seekg(pos);
file.write(reinterpret_cast<char*>(&HW), sizeof(hw));
file.flush();
break;
}
case 2:
{
vector<char> buff(sizeof(hw));
/*cout << "Id to find: ";
int id;
cin >> id;
cin.sync();
streampos pos = id*sizeof(hw);
file.seekg(pos);*/
file.seekg(0, file.end);
int size = file.tellg();
file.seekg(0, file.beg);
for (unsigned j = 0; j < size/sizeof(hw); j++)
{
file.read(&buff[0], sizeof(hw));
ZeroMemory(&HW, sizeof(hw));
memcpy(&HW, &buff[0], sizeof(hw));
buff.clear();
cout << HW.GetID() << endl << HW.GetName() << endl;
}
system("pause");
break;
}
default:
{
go = 0;
break;
}
}
}
file.close();
system("pause");
return 0;
}
|