Skip to content

Commit 33c4256

Browse files
committed
fix binary reader
1 parent fca6e0c commit 33c4256

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

BinaryFile/main.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,12 @@ int main(int argc, char **argv) {
2626
ifile->open("student.dat", std::ios::binary);
2727
if (ifile->is_open()) {
2828
Student *s = new Student();
29+
30+
// safely read file from the
31+
ifile->read(reinterpret_cast<char *>(s), sizeof(Student));
2932
while (!ifile->eof()) {
30-
ifile->read(reinterpret_cast<char *>(s), sizeof(Student));
3133
std::cout << s->whoami() << std::endl;
34+
ifile->read(reinterpret_cast<char *>(s), sizeof(Student));
3235
}
3336
} else {
3437
std::cerr << "Unable to open file\n";

BinaryFile/student.cpp

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
#include "student.hpp"
2+
#include <cstring>
23
#include <sstream>
34
#include <string>
45

56
void Student::setAge(int age) { this->age = age; }
67
void Student::setAge(short age) { this->age = age; }
78
void Student::setAge(unsigned short age) { this->age = age; }
89

9-
void Student::setName(std::string &name) { this->name = name; }
10-
void Student::setName(const char *name) { this->name = std::string(name); }
10+
void Student::setName(std::string &name) {
11+
if (name.length() < 50) {
12+
std::strcpy(this->name, name.c_str());
13+
}
14+
}
15+
void Student::setName(const char *name) {
16+
if (std::strlen(name) < 50) {
17+
std::strcpy(this->name, name);
18+
}
19+
}
1120

1221
std::string Student::whoami() const {
1322
std::stringstream s;

BinaryFile/student.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
class Student {
44
private:
5-
std::string name;
5+
char name[50];
66
unsigned short age;
77

88
public:

0 commit comments

Comments
 (0)