Search code examples
carraysfilebinaryfilesfread

How do I read from/write to a binary file in 2D Array form?


I am trying to use a binary file to hold my data in it. But I don't understand how do I read/write in 2D Array form. I know how to read arrays/structs etc. from binary files, I just don't know how do I do that with a 2D array.

I have looked at similar questions to this, but I did not understand what most of the people were getting at. I just want to know how does one read/write data in 2D Array format. as in fwrite( x , y , z , w ); .

Here is what my array looks like:

int array[50][100];

I don't know what to do from now on, if it were 1 dimensional I'd do;

FILE* fp;
fp = fopen("file.bin","wb+");
fwrite(array, sizeof(int), 50, fp);

but since that array is multi dimensional I don't actually know what to put in that function.

Thank you in advance.

Please note that I am pretty new at coding and I may not be seeing a pretty easy solution.


Solution

  • The method for saving a 2-dimensional array will be very similar to saving a 1-dimensional array, it is indeed as you wrote in the comment to the question:

    fwrite(array, sizeof(int), 50*100, fp);
    

    This is because the 2 dimensional (in this case, int)array is stored identically to how a 1 dimensional array would be; an unbroken chain of ints. However, you could save it any way you want to as long as you stay consistent with saving/loading. fwrite takes a pointer as an argument, so as long as the data you pass to it is an array it will work.