Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- matrix.h
- #if !defined MATRIX_H
- #define MATRIX_H
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdlib.h>
- #include <stdio.h>
- struct matrix
- {
- size_t rows, cols;
- double*data;
- };
- extern struct matrix** leggi_matrici(const char*filename, size_t*size);
- #endif
- matrix.c
- #include "matrix.h"
- struct matrix** leggi_matrici(const char*filename, size_t *size)
- {
- *size = 0;
- FILE* f = fopen(filename, "rt");
- if (f==NULL)
- {
- return NULL;
- }
- struct matrix** ret = NULL;
- struct matrix*tmp=malloc(sizeof(struct matrix));
- tmp->data = NULL;
- int err=0;
- int test = fscanf(f, "%u\n",size);
- if (test != 1)
- return ret;
- ret = realloc(ret,(*size) * sizeof(struct matrix*));
- unsigned count = 0;
- while (count<*size)
- {
- test = fscanf(f, "%u,%u,", &(tmp->rows),&(tmp->cols));
- if (test != 2)
- err = 1;
- tmp->data = realloc(tmp->data, (tmp->rows*tmp->cols) * sizeof(double));
- for (size_t i = 0; i < (tmp->rows*tmp->cols); i++)
- {
- test = fscanf(f, "%lf,", tmp->data + i);
- if (test != 1)
- {
- err = 1;
- break;
- }
- }
- if (err)
- {
- for (size_t i = 0; i < count; i++)
- {
- free(ret[count]);
- free(tmp->data);
- free(tmp);
- free(ret);
- return NULL;
- }
- break;
- }
- else
- {
- ret[count]=malloc(sizeof(struct matrix));
- *(ret[count]) = *tmp;
- ret[count]->data = realloc(ret[count]->data, (tmp->rows*tmp->cols) * sizeof(double));
- for (size_t i = 0; i < tmp->rows*tmp->cols; i++)
- {
- ret[count]->data[i] = tmp->data[i];
- }
- count++;
- }
- }
- return ret;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement