is_stl.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "is_stl.h"
  2. #include <string>
  3. IGL_INLINE bool igl::is_stl(FILE * stl_file, bool & is_ascii)
  4. {
  5. // solid?
  6. // YES NO
  7. // / if .stl, definitely binary
  8. // /
  9. // perfect size?
  10. // YES NO
  11. //
  12. const auto perfect_size = [](FILE * stl_file)->bool
  13. {
  14. stl_file = freopen(NULL,"rb",stl_file);
  15. // Read 80 header
  16. char header[80];
  17. if(fread(header,sizeof(char),80,stl_file)!=80)
  18. {
  19. return false;
  20. }
  21. // Read number of triangles
  22. unsigned int num_tri;
  23. if(fread(&num_tri,sizeof(unsigned int),1,stl_file)!=1)
  24. {
  25. return false;
  26. }
  27. fseek(stl_file,0,SEEK_END);
  28. int file_size = ftell(stl_file);
  29. stl_file = freopen(NULL,"r",stl_file);
  30. return (file_size == 80 + 4 + (4*12 + 2) * num_tri);
  31. };
  32. // Specifically 80 character header
  33. char header[80];
  34. char solid[80];
  35. is_ascii = true;
  36. bool f = true;
  37. if(fread(header,1,80,stl_file) != 80)
  38. {
  39. f = false;
  40. goto finish;
  41. }
  42. sscanf(header,"%s",solid);
  43. if(std::string("solid") == solid)
  44. {
  45. f = true;
  46. is_ascii = !perfect_size(stl_file);
  47. }else
  48. {
  49. is_ascii = false;
  50. f = perfect_size(stl_file);
  51. }
  52. finish:
  53. rewind(stl_file);
  54. return f;
  55. }
  56. IGL_INLINE bool igl::is_stl(FILE * stl_file)
  57. {
  58. bool is_ascii;
  59. return is_stl(stl_file,is_ascii);
  60. }