Search code examples
c++filebinarybinaryfiles

Why does my program not read binary files properly?


When i read the binary file it doesn't read anything... This is the reading:

if (file.is_open())
{
    Challenge* newChallenge;
    while (!file.eof())
    {
        file.read((char*)&newChallenge, sizeof(Challenge));
        if (!challenges.contains(newChallenge))
        {
            challenges.push_back(newChallenge);
        }
    }
    delete newChallenge;
    std::cout << "Successfully loaded " << fileName << std::endl;
    file.close();
}

This is the writing:

else if(action == "write"){
    std::ofstream file("Challenges.bin", std::ios::binary);
    if(file.is_open()){
        for (size_t i = 0; i < challenges.length(); i++)
        {
            file.write((char*)&challenges[i], sizeof(Challenge));   
        }
        std::cout << "Successfully written to file!" << std::endl;
    }else {
        std::cout << "Failed to open file!" << std::endl;
    }
    file.close();
}

And this is the challenge class:

#ifndef CHALLENGE_H
#define CHALLENGE_H
#include "String.h"

class Challenge
{
private:
    double rating = 0;
    int status = 1, finishes = 0;
    String init;

public:
    Challenge(String _init = "") : init(_init) {}

    void addToStatus() { status++; }
    void addToRating(double rate)
    {
        finishes++;
        rating = ((rating * (finishes - 1)) + rate) / finishes;
    }

    String getChallenge() { return init; }
    int getStatus() { return status; }
    double checkRating() { return rating; }
};

#endif

Note: The String class is a class that I've made myself using char*, its not from std.. I am not allowed to use the std one.


Solution

  • Challenge* newChallenge;
    while (!file.eof())
    {
        file.read((char*)&newChallenge, sizeof(Challenge));
    ...
    

    This code is declaring a pointer to a class instance not initialized to point at anything and then apparently wanted to reads over it some bytes from a disk file.

    This is very very wrong on at least three levels:

    1. you did not allocate any memory
    2. objects are not byte chunks and to create them you need to invoke constructors
    3. the reading is targeting the pointer, not the memory pointed to (there's an & in excess in the fread call)