mercredi 29 avril 2015

Getting garbage values when accessing values in array read from binary file

void RecordFile::load(ifstream& file){
if(!file.fail()){
    size_t n = 0;
    file.read(reinterpret_cast<char*>(&weeks), sizeof(weeks));
    file.read(reinterpret_cast<char*>(&n), sizeof(int));
    char buffer[256];
    file.read(reinterpret_cast<char*>(&buffer), n);
    buffer[n] = '\0';
    studentName = buffer;

    if(quiz)
        delete quiz;
    quiz = new double[weeks];
    if(assignment)
        delete assignment;

    assignment = new double[weeks];
    file.read(reinterpret_cast<char*>(quiz), sizeof(quiz));
    file.read(reinterpret_cast<char*>(assignment), sizeof(assignment));

}
else
    cout << "Failed to load file" << endl;

}

void RecordFile::store(ofstream& file){
if(!file.fail()){
    size_t n = studentName.length();
    file.write(reinterpret_cast<char*>(&weeks), sizeof(weeks));
    file.write(reinterpret_cast<char*>(&n), sizeof(n) );
    file.write(studentName.data(), n);

    file.write(reinterpret_cast<char*>(quiz), sizeof(quiz));
    file.write(reinterpret_cast<char*>(assignment), sizeof(assignment));


}
else
    cout << "Failed to load file" << endl;

}

The code reads everything but the quiz and assignment arrays perfectly. Which is a surprise to me because this is the first time I've ever tried i/o with binary files. But anyways, I'm pretty certain the values I get when I Try to output the values in the array are garbage values (6.somethinge+66).

EDIT: I'm able to access the variable by storing and reading the arrays using a for loop, which is fine, but I'd like to know if there's a way to read the entire array at one time. I'm pretty sure this has little to no impact on file size, but just for the sake of simplifying my code (and learning more) I'd like to know a better alternative.

Aucun commentaire:

Enregistrer un commentaire