Guest User

Untitled

a guest
Dec 14th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. typedef struct matrix_ {
  2. int r, c;
  3. double* dat;
  4. } matrix;
  5.  
  6. int rows(char* fn) {
  7. int lines = 1;
  8. int ch;
  9. FILE* fp = fopen(fn, "r");
  10. while(!feof(fp)) {
  11. ch = fgetc(fp);
  12. if(ch == 'n') {
  13. lines++;
  14. }
  15. }
  16. return lines;
  17. }
  18.  
  19. matrix loadmatrix(char* fn) {
  20. FILE* file = fopen(fn, "r");
  21. int size = 5*5;
  22. matrix mat;
  23. mat.r = rows(fn);
  24. mat.dat = malloc(size*sizeof(double));
  25. double input;
  26. int i = 0;
  27. do {
  28. if (fscanf(file, "%lf", &input)==1) {
  29. if(i == size-1) {
  30. size = 4*size;
  31. mat.dat = realloc(mat.dat, size*sizeof(double));
  32. }
  33. mat.dat[i] = input;
  34. i+=1;
  35. }
  36. } while (!feof(file));
  37. mat.c = ((i+1)/(mat.r));
  38. return mat;
  39. }
  40.  
  41. #define MIN_SIZE (5 * 5)
  42.  
  43. typedef struct matrix {
  44. size_t rows;
  45. size_t cols;
  46. double *data;
  47. } matrix;
  48.  
  49. matrix loadmatrix(const char *filename)
  50. {
  51. FILE *file = fopen(filename, "r");
  52. if (file == NULL) {
  53. fprintf(stderr, "could not open file '%s' for readingn", filename);
  54. exit(1);
  55. }
  56. matrix mat = {
  57. .rows = 0,
  58. .cols = 0,
  59. .data = calloc(MIN_SIZE, sizeof(double)),
  60. };
  61. // You should check mat.data != NULL here, but I omit it to ease reading
  62. char *line = NULL;
  63. size_t index = 0;
  64. size_t data_size = MIN_SIZE;
  65. while (read_line(file, &line) > 0) {
  66. double value;
  67. // Keep reading values into this row
  68. size_t offset = 0;
  69. int read_chars = 0;
  70. while (sscanf(line + offset, "%lf%n", &value, &read_chars) == 1) {
  71. offset += read_chars;
  72. if (mat.rows == 0) {
  73. ++mat.cols;
  74. }
  75. // Increase the size of the matrix by one more row if more space is needed
  76. if (index >= data_size) {
  77. data_size += mat.cols;
  78. mat.data = realloc(mat.data, sizeof(double) * data_size);
  79. if (mat.data == NULL) {
  80. fprintf(stderr,
  81. "could not allocate more space for matrix: %zun",
  82. data_size);
  83. exit(1);
  84. }
  85. }
  86. mat.data[index++] = value;
  87. }
  88. ++mat.rows;
  89. free(line);
  90. }
  91. return mat;
  92. }
Add Comment
Please, Sign In to add comment