Reading and writing binary files in c with fread-fwrite

0

I am trying to read and write binary files. I create a matrix in ram memory, then I write it in a binary file.

void escribirMatrizParcialmente(double ***A){       
    FILE *destino;
    int i,j;

    if((destino=fopen(ARCHIVOMATRIZ,"wb"))==NULL){
        printf("No se pudo abrir el archivo.");
        return;
    }
    for(i=0;i<FILAS;i++){
        fwrite( &A[i][0],sizeof(double),COLUMNAS,destino);  
        //escribo desde el primer elemento de cada fila la cantidad de 
        //columnas 
    }
  fclose(destino);
}

ARCHIVOMATRIZ , FILAS and COLUMNAS are constant.

Well this gives me a default Segmentation error.

There is no error in creating the matrix because I show it on the screen before writing it, and if I use fprintf to write to a text file it works correctly. With the code below I write the matrix correctly in a text file (I put it just to illustrate and let it be seen that my problem is with fwrite).

for(i=0;i<FILAS;i++){
    for(j=0;j<COLUMNAS;j++){
        fprintf(destino,"%.6lf ",(*A)[i][j]);
    }
    fprintf(destino,"%s","\n");
    }

Well I also have problems to read this matrix with fread with a code quite similar to writing. It does not give compilation errors or warnings but when I show the matrix it does not show anything.

    int i;
    for(i=0;i<FILAS;i++){
        fread( &A[i][0] ,sizeof(double), COLUMNAS, fuente );    
    }

I read all the rows from the matrix and store them in my matrix from the initial memory address of each row.

    
asked by Patricio 09.04.2018 в 06:03
source

1 answer

1

A is a triple pointer, then in this instruction:

fwrite( &A[i][0],sizeof(double),COLUMNAS,destino);  

You are writing a memory location instead of a value.

You say that you work with a matrix, that is, with an array of two dimensions ... this is modeled with a double array and, as I mentioned, here you are using a pointer > triple . Declaring a triple pointer in this case would only make sense if the function has to reserve memory for the array ... or release it. in any other case, for clarity, it would be advisable to use a double pointer:

void escribirMatrizParcialmente(double **A){       
    FILE *destino;
    int i,j;

    if((destino=fopen(ARCHIVOMATRIZ,"wb"))==NULL){
        printf("No se pudo abrir el archivo.");
        return;
    }
    for(i=0;i<FILAS;i++){
        fwrite( A[i][0],sizeof(double),COLUMNAS,destino);  
        //escribo desde el primer elemento de cada fila la cantidad de 
        //columnas 
    }
  fclose(destino);
}

For the other problems you lack information so the rest of the answer will have to wait.

    
answered by 09.04.2018 / 07:33
source