write 2d array to a file in C

Bobj-C picture Bobj-C · Jan 9, 2011 · Viewed 25.3k times · Source

I used to use the code below to Write an 1D array to a File:

FILE *fp;
float floatValue[5] = { 1.1F, 2.2F, 3.3F, 4.4F, 5.5F };
int i;

if((fp=fopen("test", "wb"))==NULL) {
    printf("Cannot open file.\n");
}

if(fwrite(floatValue, sizeof(float), 5, fp) != 5)
    printf("File write error.");
fclose(fp);

/* read the values */
if((fp=fopen("test", "rb"))==NULL) {
    printf("Cannot open file.\n");
}

if(fread(floatValue, sizeof(float), 5, fp) != 5) {
    if(feof(fp))
        printf("Premature end of file.");
    else
        printf("File read error.");
}
fclose(fp);

for(i=0; i<5; i++)
    printf("%f ", floatValue[i]);

My question is if i want to write and read 2D array ??

Answer

6502 picture 6502 · Jan 9, 2011

You can use the same approach... just make the following changes

float floatValue[3][5] = {{ 1.1F, 2.2F, 3.3F, 4.4F, 5.5F },
                          { 6.6F, 7.7F, 8.8F, 9.9F, 8.8F },
                          { 7.7F, 6.6F, 5.5F, 4.4F, 3.3F }};
int i,j;

...

if(fwrite(floatValue, sizeof(float), 3*5, fp) != 3*5)

...

if(fread(floatValue, sizeof(float), 3*5, fp) != 3*5) {

...

for(j=0; j<3; j++) {
    for(i=0; i<5; i++)
        printf("%f ", floatValue[j][i]);
    printf("\n");
}

Note of course that this is not the best way to save/load data especially if you want to have some compatibility between different compilers/systems or even just with the future. The topic of saving and restoring is often named serialization and with just a very small minor overhead you can get much more flexibilty especially once the data model becomes more complex.