What does data serialization do?

Viewed 1529

I'm having a hard time understanding what serialization is and does.

Let me simplify my problem. I have a struct info in my c/c++ programs, and I may store this struct data into a file save.bin or send it via socket to another computer.

struct info {
    std::string name;
    int age;
};

void write_to_file()
{
    info a = {"Steve", 10};
    ofstream ofs("save.bin", ofstream::binary);
    ofs.write((char *) &a, sizeof(a));   // am I doing it right?
    ofs.close();
}

void write_to_sock()
{
    // I don't know about socket api, but I assume write **a** to socket is similar to file, isn't it?
}

write_to_file will simply save the struct info object a to disk, making this data persistent, right? And write it to socket is pretty much the same, right?

In the above code, I don't think I used data serialization, but the data a is made persistent in save.bin anyway, right?

Question

  1. Then what's the point of serialization? Do I need it here? If yes, how should I use it?

  2. I always think that any kind of files, .txt/.csv/.exe/..., are bits of 01 in memory, which means they have binary representation naturally, so can't we simply send these files via socket directly?

Code example is highly appreciated.

6 Answers
Related