0

I'm writing a ctor that get a binary file and initialize the members of the class with the data. Unfortunately I can not figure out exactly how this works. I have 2 variables in the class one of them has type char * and the other is int. How do I know what to read first? This is what I have written so far, I would love advice.

Person::Person(ifstream& in_file)
{
    int size;
    in_file.read((char*)&size, sizeof(size));
    m_name = new char[size + 1];
    in_file.read(m_name, size);
    m_color[size] = '\0';

    in_file.read((char*)&m_age, sizeof(m_age));
user4581301
  • 31,330
  • 6
  • 30
  • 51
Mr.Blofer
  • 9
  • 1
  • you must be driven by the contents of the file. INspect the file with a hex dumper to see whats in there – pm100 Jun 03 '22 at 23:37
  • You don't understand the code you wrote? Or did you get this code from somewhere? – rustyx Jun 03 '22 at 23:38
  • You know what to read first either because you read the protocol document that describes the file format and it told you which to read first or because you wrote the program that writes these files and know which one you wrote into the file first. Anything else is pretty much guesswork/reverse engineering to see what works. – user4581301 Jun 03 '22 at 23:54
  • Unrelated: At `m_name = new char[size + 1];` can we talk you into a nice [RAII](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii) and [Rule of Five](https://en.cppreference.com/w/cpp/language/rule_of_three) observant `std::string`? It'd make your life whole orders of magnitude easier. – user4581301 Jun 03 '22 at 23:57
  • 1
    The `int` variable is the length of the string. Read it first. It gives you information on how much memory to allocate for the text. Next, use the `int` variable to block read the text into the allocated memory. The `int` variable tells you the quantity of characters to read from the file. – Thomas Matthews Jun 04 '22 at 00:11

0 Answers0