简体   繁体   中英

Reading string in binary files C++

I'm having a bad time with writing and reading from binary files in C++. I learned a lot from stack questions, but I never got it working and i'm guessing that problem resides in the reading process,

Here are the read and save methods:

  void date::save(ofstream& fo){
    fo.write((char *) &jour, sizeof(int));
    fo.write((char *)&moi, sizeof(int));
    fo.write((char *)&annee, sizeof(int));

    size_t len = heure.size();
    fo.write((char *)&len,sizeof(size_t));
    fo.write(heure.c_str(), heure.size());
}

void date::load(ifstream& fi){
    fi.read((char *)&jour, sizeof(int));
    fi.read((char *)&moi, sizeof(int));
    fi.read((char *)&annee, sizeof(int));

    size_t len;
    fi.read((char *)&len, sizeof(size_t));
    char* temp = new char[len+1];
    fi.read(temp, len);
    temp[len] = '\0';
    heure = temp;
    delete [] temp;
}

In additon: Is it possible to save classes with dynamic attributes directly with ofstream.write() functionality?

Many thanks.

The reading and writing seems to be correct on first sight, when assigning

heure = temp;

there is a problem. you allocate len+1 bytes of memory. temp points to the beginning of that memory. after your assignment (heure = temp) heure also points to that same memory. Then you call delete and from that point, any other operation may write any data to that memory (refered to as 'wild pointer').

You have to use

strcpy(heure, temp);

to copy each byte from temp to the memory that is allocated by heure. make sure of course that heure has allocated enough space to fit all the bytes of temp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM