J
J
jspie2017-04-26 11:55:04
C++ / C#
jspie, 2017-04-26 11:55:04

How to save / load data from a binary file through classes?

There is a class Students.

class Students{
public:

  void save();
  void load();

  ~Students();

  //Конструктор класса Students
  Students(string firstname, string lastname);

  //Установка имени
  void set_firstname(string);
  //Получение имени
  string get_firstname();

  //Установка фамилии
  void set_lastname(string);
  //Получение фамилии
  string get_lastname();

private:
  //Имя
  string firstname;
  //Фамилия
  string lastname;
};

The constructor itself:
Students::Students(string firstname, string lastname)
{
  Students::set_firstname(firstname);
  Students::set_lastname(lastname);
}

I figured out how to save:
void Students::save() {
  ofstream fout("Students.dat", ios::binary | ios::out);
  
  string firstname = Students::get_firstname();
  string lastname = Students::get_lastname();

  fout.write((char*)&lastname, sizeof(firstname));
  fout.write((char*)&lastname, sizeof(lastname));

  fout << std::endl;
  fout.close();
}

But there were problems with the download. The form itself refers to Main.cpp, the logic is in this file. There I already refer to Students.h.
The task is this: You need to load a list of students (from a binary file) Change any student and save it to the same file. As I understand it, you need to load the Students array into the file, then after editing any element of the array, return a new array and write it to the file.
The question itself is how to do this through classes, constructors and destructors? How to implement it correctly?
The description of the constructors and class functions are in the Students.cpp file. Program logic in Main.cpp

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nekipelov, 2017-04-26
@nekipelov

> fout.write((char*)&lastname, sizeof(firstname));
You write the internal contents of the class to the file. You can not do it this way. If you need to write a line, write like this:
But then you will need to read it. And for this you need to know its size, so you need to do this:

size_t size = firstname.size();
fout.write(reinterpret_cast<const char *>(&size), sizeof(size));
fout.write(lastname.data(), size);

Accordingly, then read the size first, and then the size bytes. But it is much easier to take www.boost.org/doc/libs/1_64_0/libs/serialization/doc/, this will avoid a lot of rake. There are all the tools for working with arrays.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question