I'm guessing the error lies in the writeBinary function where I open the file everytime I write into it. I am not sure how to create the file and have it not overwrite the existing data. My code results into reading 3, 3, 3 instead of 1,2,3.

#include <string>
#include <fstream>
#include <iostream>
using namespace std;

class Binary
{
public:
    Binary(int num);
    ~Binary();

    void writeBinary();
    void readBinary();

    string binFile;
    int value;
};

Binary::Binary(int num)
{
    value = num;
    binFile = "BinaryFile.bin";
}

Binary::~Binary()
{
}

void Binary::writeBinary()
{
    fstream outBinaryFile;
    ofstream appendFile(binFile, ios::out | ios::app);
    outBinaryFile.write((char*)&value, sizeof(value));
    outBinaryFile.close();

}

void Binary::readBinary()
{
    ifstream inFileBinary;                          //declare variable
    inFileBinary.open(binFile, ios::in);            //open binary file to be read from
    inFileBinary.read((char*)&value, sizeof(value));//read binary file

    inFileBinary.close();                           //close binary file

    cout << value << ", ";
}

int main()
{
//need this part
    Binary num1(1);
    Binary num2(2);
    Binary num3(3);

    num1.writeBinary();
    num2.writeBinary();
    num3.writeBinary();

    num1.readBinary();
    num2.readBinary();
    num3.readBinary();

    return 0;
}

Recommended Answers

All 3 Replies

I see issues with that code. For example on line 44 you close the file. OK, but up a few lines you open it so you'll read the first thing in the file. Since you don't read later values, you'll get the same item each time.

Now about writing. Lines 32 to 34 seem to be the only place you open and write but I see no accounting for when the file exists the first time so the file on each run might append but is that your intention?

There's few folk that will write the code for you. But it looks like you are not thinking it through yet.

I'm seeing an fstream object defined on line 31 without a filename or any parameters specifying how to open it, then used on lines 33 and 34, and I'm seeing an ofstream object defined on line 32 with a filename and opening parameters specified, but used nowhere. I'm guessing that's not what you intended and I'm thinking you are not writing to BinaryFile.bin at all and you are "reading" from an old file. Try deleting BinaryFile.bin, then running the program, see if you get the same results, or any.

I'm guessing you want to delete line 31 and change the object name in lines 33 and 34 to match line 32? I don't know if that's your ONLY problem, but I'm thinking it is a problem.

As suggested above, you seem to be a bit confuzzed?

Working with C++ binary files can be a little tricky,
especially at the beginning.

I'm not sure what you were supposed to do here,
but here is a little demo class
to show how one might append int values
to the end of a binary file of integers,
and to read then all back from this 'random access type bin file',
in reverse order;

// classBinary.cpp //

// using C++ 11 or better compiler //

#include <string>
#include <fstream>
#include <iostream>
#include <climits>

using namespace std;

#define debugging true

class Binary
{
private:
    string fname;
    size_t len;

    static const unsigned BYTES_IN_INT = sizeof(int);

public:
    //ctor.. with a default fname given here //
    Binary( const string& afname="BinaryFile.bin" ) : fname(afname)
    {
        ifstream fio( fname, ios::binary );
        if( fio )
        {
            fio.seekg( 0, ios::end );
            len = fio.tellg()/ BYTES_IN_INT;
#if debugging
            cout << "Opening len is: " << len << '\n';
#endif
            fio.close();
        }
        else len = 0;
    }

    void appendBin( int val );
    int readBin( streampos pos = 0 );
    size_t size() const { return len; }
    string name() const { return fname; }
} ;

void Binary::appendBin( int val )
{
    ofstream fio( fname, ios::app | ios::binary );
    if( fio )
    {
        fio.write( (char*)&val, BYTES_IN_INT );
        ++len;
        fio.close();
    }
    else cout << "Error opening, to write,  file: " << fname << "\n";
}

// returns INT_MIN if NO value swas read
int Binary::readBin( streampos pos )
{
    int val = INT_MIN;
    ifstream fio( fname, ios::in | ios::binary );
    if( fio )
    {
        if( (size_t)pos < len )
        {
            fio.seekg( BYTES_IN_INT*pos );
            fio.read( (char*)&val, BYTES_IN_INT );
        }
        else cout << "Out of bounds error!  Returning " << INT_MIN << '\n';
        fio.close();
    }
    else cout << "Error opening, to read, file: " << fname
              << "\nError flag value returned is: " << INT_MIN << '\n';
    return val;
}

int main()
{
    Binary nums; // call default ctor //

    int num = nums.size();

    cout << "Appending " << num+1 << ", " << num+2 << ", " << num+3
         << " to the end of the file: "
         << nums.name() << '\n';

    nums.appendBin(num+1);
    nums.appendBin(num+2);
    nums.appendBin(num+3);

    cout << "\nShowing all int's presently in the file:\n";

    for( int i = nums.size()-1; i >= 0; -- i )
    {
        cout << nums.readBin(i) << ' ';
    }
    cout << "\nSize now is: " << nums.size() << "  ";

    cin.get();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.