从C中的二进制文件中读取稀疏矩阵

时间:2017-08-31 16:31:46

标签: c struct sparse-matrix binaryfiles

首先,我很抱歉我的英语。

我正在尝试读取一个整数数组,它表示来自二进制文件的一些稀疏矩阵,我必须打印这个矩阵。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 20 
//on this way i have written the matrix in the binary
typedef struct{
    int lin,col;
    double val;
}termen;
typedef struct{
    int nl,nc,nn;
    termen* term;
}sparse_matrix;

void afisare_mat(sparse_matrix m){
int i,j,k = 0;
for(i = 0; i < m.nl; i++){
    for(j = 0; j < m.nc; j++){
        if(i == m.term[k].lin && j == m.term[k].col){
            printf("%3.2lf ",m.term[k].val);
            k++;
        }else{
            printf("%d ",0);
        }
    }printf("\n");
   }
}
int main(){
    /*this is the code used for write in the binary file
    //i tried to print these values and seems to be ok
    sparse_matrix m1,m2,m3;
    m1.term = malloc(2*sizeof(termen));
    m1.nl = 3;
    m1.nc = 3;
    m1.nn = 2;
    m1.term[0].lin = 0;
    m1.term[0].col = 1;
    m1.term[0].val = 3.2;
    m1.term[1].lin = 1;
    m1.term[1].col = 2;
    m1.term[1].val = 5.6;
    afisare_mat(m1);
    m2.term = malloc(3*sizeof(termen));
    m2.nl = 4;
    m2.nc = 4;
    m2.nn = 3;
    m2.term[0].lin = 0;
    m2.term[0].col = 0;
    m2.term[0].val = 1.9;
    m2.term[1].lin = 1;
    m2.term[1].col = 2;
    m2.term[1].val = 0.5;
    m2.term[2].lin = 2;
    m2.term[2].col = 3;
    m2.term[2].val = 6.960;
    afisare_mat(m2);
    m3.term = malloc(1*sizeof(termen));
    m3.nl = 3;
    m3.nc = 3;
    m3.nn = 1;
    m3.term[0].lin = 1;
    m3.term[0].col = 2;
    m3.term[0].val = 6.75;7
    afisare_mat(m3);
    FILE *f = fopen("in.bin","wb");
    fwrite(&m1,sizeof(sparse_matrix),1,f);
    fwrite(&m2,sizeof(sparse_matrix),1,f);
    fwrite(&m3,sizeof(sparse_matrix),1,f);
    fclose(f);
    */
    FILE *f = fopen("in.bin","rb");
    int n, v[10], i, j, k,nr = 0,it; //n=number of matrix asked, v=array with  
    //number(s)(<= n) of matrix which have to print
    scanf("%d",&n);
    sparse_matrix m;
    while(fread(&k,sizeof(int),1,f) > 0){
        fseek(f,2*sizeof(int),SEEK_CUR);
        fseek(f,sizeof(termen*),SEEK_CUR);
        nr++;
    }
    for(i = 0; i < n; i++){
        scanf("%d",&v[i]);
        if(v[i] > nr)
            printf("That matrix not exist\n");
    }

    fseek(f,0,0);
    j = 0;
    while(fread(&k,sizeof(int),1,f) > 0){   //citesc nl din fiecare matrice
        for(i = 0; i < n; i++){
            if(j == v[i]){  //number of matrix which i read;
                //print matrix

                m.nl = k;
                fread(&m.nc,sizeof(int),1,f);
                fread(&m.nn,sizeof(int),1,f);
                m.term = malloc(m.nn*sizeof(termen));
                fread(m.term,sizeof(termen),m.nn,f);
                afisare_mat(m);
                free(m.term);
                fseek(f,(j+1)*sizeof(sparse_matrix),0);
            }
        }j++;
    }
    fclose(f);
    return 0;
}

此代码在我的屏幕上打印矩阵但充满零的形式。我认为其余的元素(!= 0)无法从二进制文件中读取。你能帮帮我吗?

0 个答案:

没有答案