I'm trying to write 2 dimensional array of int type to a binary type file.

int array[3][3]={Some data};

ofstream f;

f.open("nameoffile.dat",ios::binary||ios::out);

for(i=0;i<=3;i++)
{
for(j=0;j<=3;j++)
{
f.write((char *)&array[i][j],sizeof(array));
}
}
f.close();

Above code is not complete. I only wrote a part of the code where I need help. Is this code right? It does save some data inside the file. But when I try to read it, it displays 0. Nothing else.

ifstream f;
f.open("nameoffile.dat",ios::binary||ios::in);

    for(i=0;i<=3;i++)
    {
    for(j=0;j<=3;j++)
    {
    f.read((char *)&array[i][j],sizeof(array));
    }
    }

    for(i=0;i<=3;i++)
    {
    for(j=0;j<=3;j++)
    {
    cout<<array[i][j];
    }
    }

    f.close();

What do you think?

Recommended Answers

All 3 Replies

Line 5 should be f.open("nameoffile.dat",ios::binary|ios::out); I guess.
| being the bitwise operator.

I think you have made another mistake: Consider the line of code

 f.write((char *)&array[i][j],sizeof(array));

Now for your test example you have an array of [3][3], which if we assume you have 4 byte integers: sizeof(array) evaluates to 36.

Ok so you then take each point on the array in turn and write out 36
characters (9 integers). I am certain that is not what you wanted.

Try without the loop:

f.write(reinterpret_cast<char *>(array),sizeof(array));

Same is true for your read statement.

I changed "||" to "|" in the program and it worked. The array do save and can be read from the file. And with the help of StuXYZ, I removed the loop and pasted your line of code and it worked too.

int array[3][3]={Some data};

ofstream f;

f.open("nameoffile.dat",ios::binary|ios::out);

f.write(reinterpret_cast<char *>(array),sizeof(array));

f.close();

Thanks to both of you for helping me.

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.