readDMAT.cpp 1.7 KB

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