Advertisement
Guest User

Untitled

a guest
Jul 16th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. matrix.h
  2. #if !defined MATRIX_H
  3. #define MATRIX_H
  4. #define _CRT_SECURE_NO_WARNINGS
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7.  
  8. struct matrix
  9. {
  10. size_t rows, cols;
  11. double*data;
  12. };
  13. extern struct matrix** leggi_matrici(const char*filename, size_t*size);
  14. #endif
  15.  
  16. matrix.c
  17. #include "matrix.h"
  18. struct matrix** leggi_matrici(const char*filename, size_t *size)
  19. {
  20. *size = 0;
  21. FILE* f = fopen(filename, "rt");
  22. if (f==NULL)
  23. {
  24. return NULL;
  25. }
  26. struct matrix** ret = NULL;
  27. struct matrix*tmp=malloc(sizeof(struct matrix));
  28. tmp->data = NULL;
  29. int err=0;
  30. int test = fscanf(f, "%u\n",size);
  31. if (test != 1)
  32. return ret;
  33. ret = realloc(ret,(*size) * sizeof(struct matrix*));
  34. unsigned count = 0;
  35. while (count<*size)
  36. {
  37. test = fscanf(f, "%u,%u,", &(tmp->rows),&(tmp->cols));
  38. if (test != 2)
  39. err = 1;
  40. tmp->data = realloc(tmp->data, (tmp->rows*tmp->cols) * sizeof(double));
  41. for (size_t i = 0; i < (tmp->rows*tmp->cols); i++)
  42. {
  43. test = fscanf(f, "%lf,", tmp->data + i);
  44. if (test != 1)
  45. {
  46. err = 1;
  47. break;
  48. }
  49. }
  50. if (err)
  51. {
  52. for (size_t i = 0; i < count; i++)
  53. {
  54. free(ret[count]);
  55. free(tmp->data);
  56. free(tmp);
  57. free(ret);
  58. return NULL;
  59. }
  60. break;
  61. }
  62. else
  63. {
  64. ret[count]=malloc(sizeof(struct matrix));
  65. *(ret[count]) = *tmp;
  66. ret[count]->data = realloc(ret[count]->data, (tmp->rows*tmp->cols) * sizeof(double));
  67. for (size_t i = 0; i < tmp->rows*tmp->cols; i++)
  68. {
  69. ret[count]->data[i] = tmp->data[i];
  70. }
  71. count++;
  72. }
  73. }
  74.  
  75. return ret;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement