readDMAT.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "readDMAT.h"
  2. #include "verbose.h"
  3. #include <cstdio>
  4. IGL_INLINE bool igl::readDMAT(const std::string file_name, Eigen::MatrixXd & W)
  5. {
  6. FILE * fp = fopen(file_name.c_str(),"r");
  7. if(fp == NULL)
  8. {
  9. fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
  10. return false;
  11. }
  12. // first line contains number of rows and number of columns
  13. int num_cols, num_rows;
  14. int res = fscanf(fp,"%d %d\n",&num_cols,&num_rows);
  15. if(res != 2)
  16. {
  17. fclose(fp);
  18. fprintf(stderr,"IOError: readDMAT() first row should be [num cols] [num rows]...\n");
  19. return false;
  20. }
  21. // check that number of columns and rows are sane
  22. if(num_cols < 0)
  23. {
  24. fclose(fp);
  25. fprintf(stderr,"IOError: readDMAT() number of columns %d < 0\n",num_cols);
  26. return false;
  27. }
  28. if(num_rows < 0)
  29. {
  30. fclose(fp);
  31. fprintf(stderr,"IOError: readDMAT() number of rows %d < 0\n",num_rows);
  32. return false;
  33. }
  34. // Resize output to fit matrix
  35. W.resize(num_rows,num_cols);
  36. // Loop over columns slowly
  37. for(int j = 0;j < num_cols;j++)
  38. {
  39. // loop over rows (down columns) quickly
  40. for(int i = 0;i < num_rows;i++)
  41. {
  42. if(fscanf(fp," %lg",&W(i,j)) != 1)
  43. {
  44. fclose(fp);
  45. fprintf(
  46. stderr,
  47. "IOError: readDMAT() bad format after reading %d entries\n",
  48. j*num_rows + i);
  49. return false;
  50. }
  51. }
  52. }
  53. fclose(fp);
  54. return true;
  55. }