write 2d array to a file in C

前端 未结 2 1818
清歌不尽
清歌不尽 2021-02-04 15:52

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\", \"w         


        
相关标签:
2条回答
  • 2021-02-04 16:21

    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");}
    
    0 讨论(0)
  • 2021-02-04 16:38

    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.

    0 讨论(0)
提交回复
热议问题