guess_extension.cpp 2.3 KB

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