Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write 2d array to a file in C

Tags:

c

io

stdio

fwrite

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

like image 565
Bobj-C Avatar asked Jan 09 '11 09:01

Bobj-C


2 Answers

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.

like image 189
6502 Avatar answered Oct 07 '22 21:10

6502


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");}
like image 24
Iraklis Avatar answered Oct 07 '22 19:10

Iraklis