C ++ Saving Objects in a File

I have a list of objects that I would like to save in the file as little as possible for later search. I read this tutorial carefully , and am starting (I think) to understand, but I have a few questions. Here is a snippet I'm working with:

    static bool writeHistory(string fileName)
{
    fstream historyFile;
    historyFile.open(fileName.c_str(), ios::binary);
    if (historyFile.good())
    {
        list<Referral>::iterator i;
        for(i = AllReferrals.begin(); 
                i != AllReferrals.end();
                i++)
        {
            historyFile.write((char*)&(*i),sizeof(Referral));
        }
        return true;
    } else return false;
}

Now it is adapted from fragment

file.write((char*)&object,sizeof(className));

taken from a textbook. Now I suppose this does the conversion of the object to a pointer, taking the value and size and writing it to a file. But if so, why do the conversions at all? Why not take value from the start? And why does he need size? Also, from my understanding of why,

historyFile.write((char*)i,sizeof(Referral));

not compile? I am an iterator (and not a pointer iterator?). or simply

historyFile.write(i,sizeof(Referral));

? ? / , , , ?

.txt? <edit> , ? .dtb . </edit> ios:: binary. ( , c_str(), , ).

, ?

+3
6

, , . Boost .

, , , , . POD. , , .

(char*)&(*i)

, i, , , . , . sizeof(Referral) - , .

, , .

+7

โ„–1 ... ? : * - :: ;; , .

โ„–2 .txt? : , ..txt MIME/plain.

: ? : Referral , . "" , , - , , -, , . .

+2

?

- , . (, ) , . -, , - , .

, , . - , , , . , , .

, , (char*)&(*i).

  • *i , .
  • & , .
  • (char*) char.

- :

Referral& r = *i;
Referral* pr = &r;
char* pc = (char*)pr;

?

?

fstream::write . , . , , , , . , , .

, :

MyClass ExampleObject;
file.write((char*)ExampleObject, sizeof(ExampleObject));

, ExampleObject .

. , , , , , fstream::write.


?

, . , , , , . , .

- , :

  • , , . , , .
  • , , ? , 2 1. , (, ), 1, 2, .
  • ? , . , , . .

, . (, XML). , , .

+2
+1

boost:: serialization, , , , XML- , .

+1

Fstream.write . - . - ( ) , , .

file.write((char*)&object,sizeof(className));

^ char.

historyFile.write((char*)i,sizeof(Referral));

^ (i) char ()

historyFile.write(i,sizeof(Referral));

^ , char.

0
source

Source: https://habr.com/ru/post/1718737/


All Articles