-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
691 lines (639 loc) · 19.7 KB
/
main.cpp
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/*
Author: Mostafa Omar Mahmoud - 20170292
Date: Apr. 13th 2019
Version 1.1
Fields & Record organization with File Structures using C++
Manages 'Course' records with the following attributes:
Course ID (Primary Key)
Course Name
Instructor Name (Secondary Key)
Number of weeks
Method of Organization: Length indicator records, delimeted fields
Operations:
Print All Courses
Add Course Delete Course
(by Course ID) Update Course
(by Course ID Print Course (by Course ID)
Delete Course (by instructor name)
Update Course (by instructor name) Print Course (by instructor name)
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const char fieldDelimeter = '|';
struct Course{
char courseID[6];
string courseName, instructorName;
short weeks;
};
istream& operator>> (istream &in, Course &crs)
{
cout << "Enter Course ID (5 chars): ";
in >> crs.courseID;
in.ignore();
cout << "Enter Course Name: ";
getline(in, crs.courseName); // Don't forget to handle ignores
cout << "Enter Instructor Name: ";
getline(in, crs.instructorName);
cout << "Enter Number of Weeks: ";
in >> crs.weeks;
return in;
}
ostream& operator<< (ostream &out, const Course &crs)
{
out << "Course ID: " << crs.courseID << '\n';
out << "Course Name: " << crs.courseName << '\n';
out << "Instructor Name: " << crs.instructorName << '\n';
out << "Number of Weeks: " << crs.weeks << '\n';
}
void addCourse(fstream &fout, const Course &crs)
{
string buffer;
buffer.append(crs.courseID);
buffer += fieldDelimeter;
buffer += crs.courseName;
buffer += fieldDelimeter;
buffer += crs.instructorName;
buffer += fieldDelimeter;
short recordSize = buffer.size() + sizeof(crs.weeks) + sizeof(fieldDelimeter);
fout.write((char*)&recordSize, sizeof(recordSize));
fout.write(buffer.c_str(), buffer.size());
fout.write((char*)&crs.weeks, sizeof(crs.weeks));
fout.put(fieldDelimeter);
}
/*
* Reads a course record and returns its size
* returns 0 in case of failure of reading
*/
short readCourse(fstream &fin, Course &crs)
{
short recordSize;
fin.read((char*)&recordSize, sizeof(recordSize));
if (fin.fail() || fin.eof())
return 0;
// recordSizecourseID|courseName|instructorName|weeks|
fin.getline(crs.courseID, 6, fieldDelimeter);
getline(fin, crs.courseName, fieldDelimeter);
getline(fin, crs.instructorName, fieldDelimeter);
fin.read((char*)&crs.weeks, sizeof(crs.weeks));
fin.ignore();
return recordSize;
}
bool exists(const string &filePath)
{
fstream myFile(filePath.c_str(), ios::binary|ios::in|ios::out);
if (myFile.fail())
return false;
else
{
myFile.close();
return true;
}
}
/*
* returns false if file already exists
* Creates a file and returns true otherwise
*/
bool createFile(const string &filePath)
{
if (exists(filePath))
return false;
ofstream fout(filePath, ios::binary);
fout.close();
return true;
}
/*
* File Manager for data of type Course
* Method of Organization: Length indicator records, delimeted fields
*/
class CourseFileManager
{
private:
struct PrimaryIndexRecord
{
char courseID[6];
int offset; // OFFSET IS INT CAREFUL
PrimaryIndexRecord(char __courseID[6] = "", int __offset = 0)
{
strcpy(courseID, __courseID);
offset = __offset;
}
bool operator< (const PrimaryIndexRecord &other) const{
short cmp = strcmp(courseID, other.courseID);
if (cmp != 0)
return cmp < 1;
return offset < other.offset;
}
};
struct SecondaryIndex
{
string instructorName;
short RRN; // RRN of the first record in the LabeLID file
SecondaryIndex(string __instructorName, short __RRN)
{
instructorName = __instructorName;
RRN = __RRN;
}
bool operator <(const SecondaryIndex &other) const{
if (instructorName != other.instructorName)
return instructorName < other.instructorName;
return RRN < other.RRN;
}
};
struct LabelID{
char courseID[6];
short next;
LabelID(char __courseID[6] = "", short __next = 0)
{
strcpy(courseID, __courseID);
next = __next;
}
};
vector<PrimaryIndexRecord> vPrimaryIndex;
vector<SecondaryIndex> vSecondaryIndex;
vector<LabelID> vLabelID;
string dataFilePath, primaryIndexFilePath, secondaryIndexFilePath, labelIDFilePath;
/*
* Checks if primary index file corresponds to the current data file
* Returns 0 if it's not up to date, -1 if it doesn't exist, -2 if it exists but empty, 1 if it is up to date
*/
int isPrimaryUpToDate()
{
if (!exists(primaryIndexFilePath))
return -1;
ifstream fin(primaryIndexFilePath.c_str(), ios::binary);
bool notUpToDateHeader;
fin.read((char*)¬UpToDateHeader, sizeof(notUpToDateHeader));
if (fin.fail() || fin.eof()) // file exists but empty
return -2;
fin.close();
return !notUpToDateHeader;
}
void changePrimaryIndexHeader(bool state)
{
fstream fout(primaryIndexFilePath, ios::in|ios::out|ios::binary);
fout.write((char*)&state, sizeof(state));
fout.close();
}
/*
* constructs a primary index file from the data file
* NOTES:
* You should handle creating the file before calling this function
* You should load primary index into main memory after calling this function
*/
void reconstructPrimaryIndex()
{
ofstream fout(primaryIndexFilePath.c_str(), ios::binary);
fstream fin(dataFilePath.c_str(), ios::binary|ios::in|ios::out);
bool notUpToDateHeader = false;
fout.write((char*)¬UpToDateHeader, sizeof(notUpToDateHeader));
Course crs;
while(true)
{
int address = fin.tellg();
short recordSize = readCourse(fin, crs);
if (recordSize == 0)
break;
if (crs.courseID[0] != '*')
{
fout.write(crs.courseID, sizeof(crs.courseID));
fout.write((char*)&address, sizeof(address));
}
}
fout.close();
fin.close();
}
/*
* Loads primary index file in memory
* NOTE: You should handle whether primary index file is up to date or not before calling this function
*/
void loadPrimaryIndex()
{
vPrimaryIndex.clear();
ifstream fin(primaryIndexFilePath.c_str(), ios::binary);
fin.seekg(1, ios::beg); // skips header
PrimaryIndexRecord temp;
while(true)
{
fin.read(temp.courseID, sizeof(temp.courseID));
if (fin.fail() || fin.eof())
break;
fin.read((char*)&temp.offset, sizeof(temp.offset));
vPrimaryIndex.push_back(temp);
}
fin.close();
sort(vPrimaryIndex.begin(), vPrimaryIndex.end());
}
void savePrimaryIndex()
{
ofstream fout(primaryIndexFilePath.c_str(), ios::binary);
bool notUpToDate = false;
fout.write((char*)¬UpToDate, sizeof(notUpToDate));
for (auto r : vPrimaryIndex)
{
fout.write(r.courseID, sizeof(r.courseID));
fout.write((char*)&r.offset, sizeof(r.offset));
}
fout.close();
}
int PrimaryKeyBinarySearch(char *courseID)
{
int l = 0, r = (int)vPrimaryIndex.size() - 1;
while(l <= r)
{
int mid = (l + r)/2;
short cmp = strcmp(courseID, vPrimaryIndex[mid].courseID);
if (cmp == 0)
return mid;
else if (cmp == -1)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
int SecondaryKeyBinarySearch(const string &name)
{
int l = 0, r = (int)vSecondaryIndex.size() - 1;
while (l <= r)
{
int mid = (l + r)/2;
if (vSecondaryIndex[mid].instructorName == name)
return mid;
else if (name < vSecondaryIndex[mid].instructorName)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
/*
* loads secondary index in main memory
*/
void loadSecondaryIndex()
{
vLabelID.clear();
vSecondaryIndex.clear();
fstream fin(dataFilePath.c_str(), ios::binary|ios::in|ios::out);
Course crs;
while(true)
{
if (!readCourse(fin, crs))
break;
if (crs.courseID[0] =='*')
continue;
short next = -1;
int idx = SecondaryKeyBinarySearch(crs.instructorName);
if (idx == -1)
{
SecondaryIndex r(crs.instructorName, vLabelID.size());
vSecondaryIndex.push_back(r);
sort(vSecondaryIndex.begin(), vSecondaryIndex.end());
}
else
{
next = vSecondaryIndex[idx].RRN;
vSecondaryIndex[idx].RRN = vLabelID.size();
}
vLabelID.push_back(LabelID(crs.courseID, next));
}
fin.close();
}
void saveSecondaryIndex()
{
ofstream outSecondary(secondaryIndexFilePath.c_str(), ios::binary);
ofstream outLabel(labelIDFilePath.c_str(), ios::binary);
bool notUpToDate = false;
outSecondary.write((char*)¬UpToDate, sizeof(notUpToDate));
for (auto r : vSecondaryIndex)
{
if (r.RRN != -1)
{
outSecondary.write(r.instructorName.c_str(), r.instructorName.size());
outSecondary.write((char *) &r.RRN, sizeof(r.RRN));
}
}
outSecondary.close();
for (auto r : vLabelID)
{
outLabel.write(r.courseID, sizeof(r.courseID));
outLabel.write((char*)&r.next, sizeof(r.next));
}
outLabel.close();
}
void changeSecondaryIndexHeader(bool header)
{
fstream fout(secondaryIndexFilePath.c_str(), ios::out|ios::in|ios::binary);
fout.write((char*)&header, sizeof(header));
fout.close();
}
int isSecondaryUpToDate()
{
if (!exists(secondaryIndexFilePath))
return -1;
ifstream fin(secondaryIndexFilePath.c_str(), ios::binary);
bool notUpToDateHeader;
fin.read((char*)¬UpToDateHeader, sizeof(notUpToDateHeader));
if (fin.fail() || fin.eof()) // file exists but empty
return -2;
fin.close();
return !notUpToDateHeader;
}
void reconstructSecondaryIndex()
{
loadSecondaryIndex();
saveSecondaryIndex();
}
void insertSecondary(Course &crs)
{
int idx = SecondaryKeyBinarySearch(crs.instructorName);
int next = -1;
if (idx == -1)
{
vSecondaryIndex.push_back(SecondaryIndex(crs.instructorName, vLabelID.size()));
sort(vSecondaryIndex.begin(), vSecondaryIndex.end());
}
else
{
next = vSecondaryIndex[idx].RRN;
vSecondaryIndex[idx].RRN = vLabelID.size();
}
vLabelID.push_back(LabelID(crs.courseID, next));
}
public:
CourseFileManager(string _dataFilePath = "defaultDataFile")
{
dataFilePath = _dataFilePath;
primaryIndexFilePath = dataFilePath + "PrimaryIndex.txt";
secondaryIndexFilePath = dataFilePath + "SecondaryIndex.txt";
labelIDFilePath = dataFilePath + "LabelID.txt";
dataFilePath += ".txt";
createFile(dataFilePath);
createFile(primaryIndexFilePath);
createFile(secondaryIndexFilePath);
createFile(labelIDFilePath);
if (isPrimaryUpToDate() != 1)
{
reconstructPrimaryIndex();
loadPrimaryIndex();
}
else
loadPrimaryIndex();
if (isSecondaryUpToDate() != 1)
{
reconstructSecondaryIndex();
}
else
loadSecondaryIndex();
}
void addRecord(Course &crs)
{
changePrimaryIndexHeader(true);
changeSecondaryIndexHeader(true);
fstream fout(dataFilePath, ios::in|ios::out|ios::binary);
fout.seekp(0, ios::end);
int address = fout.tellp();
addCourse(fout, crs);
int i = 0;
PrimaryIndexRecord r(crs.courseID, address);
vPrimaryIndex.push_back(r);
sort(vPrimaryIndex.begin(), vPrimaryIndex.end());
insertSecondary(crs);
fout.close();
}
/*
* returns false if record is not found
*/
bool deleteRecord(char courseID[])
{
int idx = PrimaryKeyBinarySearch(courseID);
if (idx == -1)
return false;
changePrimaryIndexHeader(true);
int address = vPrimaryIndex[idx].offset;
fstream fout(dataFilePath, ios::in|ios::out|ios::binary);
fout.seekp(address + 2, ios::beg); // skips record length and adds '*' to the beginning of courseID
fout.put('*');
vPrimaryIndex.erase(vPrimaryIndex.begin() + idx);
fout.close();
return true;
}
/*
* returns false if record is not found
*/
bool updateRecord(char courseID[], Course &crs, bool keepID = false)
{
if (!deleteRecord(courseID))
return false;
changePrimaryIndexHeader(true);
if (keepID)
strcpy(crs.courseID, courseID);
addRecord(crs);
return true;
}
void printAll()
{
fstream fin(dataFilePath, ios::in|ios::out|ios::binary);
Course crs;
int i = 0;
while(true)
{
if (!readCourse(fin, crs))
break;
if (crs.courseID[0] == '*')
continue;
cout << "Course #" << ++i << ":\n";
cout << crs << '\n';
}
fin.close();
}
bool printByCourseID(char courseID[])
{
int idx = PrimaryKeyBinarySearch(courseID);
if (idx == -1)
return false;
int address = vPrimaryIndex[idx].offset;
fstream fin(dataFilePath, ios::in|ios::out|ios::binary);
fin.seekg(address, ios::beg);
Course crs;
readCourse(fin, crs);
cout << crs << '\n';
return true;
}
~CourseFileManager()
{
savePrimaryIndex();
saveSecondaryIndex();
}
bool printByInstructorName(const string &name)
{
int idx = SecondaryKeyBinarySearch(name);
if (idx == -1)
return 0;
for (int k = vSecondaryIndex[idx].RRN; k != -1; k = vLabelID[k].next)
printByCourseID(vLabelID[k].courseID);
return 1;
}
bool updateRecordByInstructorName(const string &name, Course &crs)
{
int idx = SecondaryKeyBinarySearch(name);
if (idx == -1)
return 0;
for (int k = vSecondaryIndex[idx].RRN; k != -1; k = vLabelID[k].next)
updateRecord(vLabelID[k].courseID, crs);
return 1;
}
bool deleteRecordByInstructorName(const string &name)
{
int idx = SecondaryKeyBinarySearch(name);
if (idx == -1)
return 0;
for (int k = vSecondaryIndex[idx].RRN; k != -1; k = vLabelID[k].next)
deleteRecord(vLabelID[k].courseID);
return 1;
}
};
void printMenu()
{
cout << "\nWhat would you like to do now?\n\n"
"1- Print All Courses\n"
"2- Add Course\n"
"3- Delete Course (by Course ID)\n"
"4- Update Course (by Course ID\n"
"5- Print Course (by Course ID)\n"
"6- Delete Course (by instructor name)\n"
"7- Update Course (by instructor name)\n"
"8- Print Course (by instructor name)\n"
"9- Close current file\n"
"0- Exit\n\n";
}
string askForFilePath()
{
cout << "Please Enter File Path: ";
string filePath;
cin >> filePath;
return filePath;
}
int main()
{
CourseFileManager* manager = 0;
bool done = false;
while(!done)
{
if (manager == 0)
{
string filePath = askForFilePath();
manager = new CourseFileManager(filePath);
}
else
{
printMenu();
int choice;
cout << "Enter choice: ";
cin >> choice;
switch (choice)
{
case 0:
{
done = true;
delete manager;
break;
}
case 1:
{
manager->printAll();
break;
}
case 2:
{
Course crs;
cin >> crs;
manager->addRecord(crs);
cout << "Record added!\n";
break;
}
case 3:
{
char courseID[6];
cout << "Enter course ID to delete: ";
cin >> courseID;
if (manager->deleteRecord(courseID))
cout << "Course Deleted!\n";
else
cout << "Course not found!\n";
break;
}
case 4:
{
char courseID[6];
cout << "Enter course ID to update: ";
cin >> courseID;
cout << "Enter new course: \n";
Course crs;
cin >> crs;
if (manager->updateRecord(courseID, crs))
cout << "Course updated!\n";
else
cout << "Course not found!\n";
break;
}
case 5:
{
char courseID[6];
cout << "Enter course ID to print: ";
cin >> courseID;
if (!manager->printByCourseID(courseID))
cout << "Course not found!\n";
break;
}
case 6:
{
string name;
cout << "Enter instructor name: ";
cin.ignore(32767, '\n');
getline(cin, name);
manager->deleteRecordByInstructorName(name);
break;
}
case 7:
{
string name;
cout << "Enter instructor name: ";
cin.ignore(32767, '\n');
getline(cin, name);
Course crs;
cout << "Enter new course: \n";
cin >> crs;
manager->updateRecordByInstructorName(name, crs);
break;
}
case 8:
{
string name;
cout << "Enter instructor name: ";
cin.ignore(32767, '\n');
getline(cin, name);
manager->printByInstructorName(name);
break;
}
case 9:
{
delete manager;
manager = 0;
cout << "File closed!\n";
break;
}
default:
{
cout << "Invalid Choice!\n";
break;
}
}
}
}
return 0;
}