-3

I'm studying c++. there is a source code of refecterging_44 class.

#include <iostream>
#include <string>

using namespace std;

class refecterging_44 {

public:
refecterging_44() {
    m_1 = "sdgsdg";
    m_2 = 100;
    m_3 = 123123;
    num = sizeof(refecterging_44);
    ptr = &m_1[0];
}
refecterging_44(string name, int score, int id, size_t num, char* ptr) {
    refecterging_44::m_1 = m_1;
    refecterging_44::m_2 = m_2;
    refecterging_44::m_3 = m_3;
    refecterging_44::num = num;
    refecterging_44::ptr = ptr;
}

void write(ostream& os) {
    os.write((char*)this, sizeof(refecterging_44));
    os.write((char*)ptr, num);
}

void read(istream& is) {
    is.read((char*)this, sizeof(refecterging_44));
    is.read((char*)ptr, num);
}

private:
    string m_1;
    int m_2;
    int m_3;
    size_t num;
    char* ptr;

};

'm_1', 'm_2', 'm_3' are just samples of object about each data value. and 'num' is bytes of memory were Assigned, 'ptr' is address of beginning memory

if I saved the data in txt or other file with write(), how I read this data in the file? can't read the file with my read() function.

When Need additional information, I will comment. Sorry about my silly question. Please understand my low level explanation, because my knowledge is low level... :(

kkkkkk
  • 19
  • 4
  • `ptr` and `num` are both not needed. If you get rid of those, it makes the code much easier. – NathanOliver Apr 19 '21 at 16:38
  • "can't read the file with my read() function" -- without seeing how you are trying to *use* your `read()` function, don't expect much help on that. – Scott Hunter Apr 19 '21 at 16:39
  • 1
    You can't save pointers, or object containing pointers (like `std::string`), as raw data. On a modern operating system all pointers are local to a single process, and what is saved is the *pointer itself* and not what it points to. – Some programmer dude Apr 19 '21 at 16:40

1 Answers1

0

Files are streams of bytes. If you want to save data to a file, you need to define a file format as a stream of bytes, convert your data into that format, and write that stream of bytes to a file. Your code never does that.

What your code does is take however the computer happens to store an object internally and stores it in a file. That's not helpful because it likely contains references to other bits of information that are in memory at that time and might not be when you try to read the data back in. I might remember "23" as "the street number of the house I grew up in" but that's not a useful way to convey the number 23 to others. You have to write code to convert into a known format.

This is called "serialization" and there are lots of great formats and libraries for it.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278