guess_extension.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. #include "guess_extension.h"
  2. #include <string.h>
  3. #include "is_stl.h"
  4. #include "ply.h"
  5. IGL_INLINE void igl::guess_extension(FILE * fp, std::string & guess)
  6. {
  7. const auto is_off = [](FILE * fp)-> bool
  8. {
  9. char header[1000];
  10. const std::string OFF("OFF");
  11. const std::string NOFF("NOFF");
  12. const std::string COFF("COFF");
  13. bool f = (fscanf(fp,"%s\n",header)==1 && (
  14. std::string(header).compare(0, OFF.length(), OFF)==0 ||
  15. std::string(header).compare(0, COFF.length(), COFF)==0 ||
  16. std::string(header).compare(0,NOFF.length(),NOFF)==0));
  17. rewind(fp);
  18. return f;
  19. };
  20. const auto is_ply = [](FILE * ply_file) -> bool
  21. {
  22. int nelems;
  23. char ** elem_names;
  24. igl::ply::PlyFile * in_ply = igl::ply::ply_read(ply_file,&nelems,&elem_names);
  25. if(in_ply==NULL)
  26. {
  27. return false;
  28. }
  29. free(in_ply);
  30. rewind(ply_file);
  31. return true;
  32. };
  33. const auto is_wrl = [](FILE * wrl_file)->bool
  34. {
  35. bool still_comments = true;
  36. char line[1000];
  37. std::string needle("point [");
  38. std::string haystack;
  39. while(still_comments)
  40. {
  41. if(fgets(line,1000,wrl_file) == NULL)
  42. {
  43. rewind(wrl_file);
  44. return false;
  45. }
  46. haystack = std::string(line);
  47. still_comments = std::string::npos == haystack.find(needle);
  48. }
  49. rewind(wrl_file);
  50. return true;
  51. };
  52. const auto is_mesh = [](FILE * mesh_file )->bool
  53. {
  54. char line[2048];
  55. // eat comments at beginning of file
  56. bool still_comments= true;
  57. while(still_comments)
  58. {
  59. if(fgets(line,2048,mesh_file) == NULL)
  60. {
  61. rewind(mesh_file);
  62. return false;
  63. }
  64. still_comments = (line[0] == '#' || line[0] == '\n');
  65. }
  66. char str[2048];
  67. sscanf(line," %s",str);
  68. // check that first word is MeshVersionFormatted
  69. if(0!=strcmp(str,"MeshVersionFormatted"))
  70. {
  71. rewind(mesh_file);
  72. return false;
  73. }
  74. rewind(mesh_file);
  75. return true;
  76. };
  77. guess = "obj";
  78. if(is_mesh(fp))
  79. {
  80. guess = "mesh";
  81. }else if(is_off(fp))
  82. {
  83. guess = "off";
  84. }else if(is_ply(fp))
  85. {
  86. guess = "ply";
  87. }else if(igl::is_stl(fp))
  88. {
  89. guess = "stl";
  90. }else if(is_wrl(fp))
  91. {
  92. guess = "wrl";
  93. }
  94. // else obj
  95. rewind(fp);
  96. }
  97. IGL_INLINE std::string igl::guess_extension(FILE * fp)
  98. {
  99. std::string guess;
  100. guess_extension(fp,guess);
  101. return guess;
  102. }