write 2d array to a file in C

27,837

Solution 1

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.

Solution 2

Instead of a single for loop you will add an other one e.g.:

for(i=0;i<lines;i++) {
for(j=0;j<num;j++) {
    fprintf(file,"%d ",array[i][j]);
}
fprintf(file,"\n");}
Share:
27,837
Bobj-C
Author by

Bobj-C

iOS developer

Updated on July 09, 2022

Comments

  • Bobj-C
    Bobj-C almost 2 years

    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 ??

  • EvilTeach
    EvilTeach about 12 years
    while this is reasonable code, the op is looking for something to write/read the binary representation of the array.