is_stl.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. fseek(stl_file,0,SEEK_SET);
  30. //stl_file = freopen(NULL,"r",stl_file);
  31. return (file_size == 80 + 4 + (4*12 + 2) * num_tri);
  32. };
  33. // Specifically 80 character header
  34. char header[80];
  35. char solid[80];
  36. is_ascii = true;
  37. bool f = true;
  38. if(fread(header,1,80,stl_file) != 80)
  39. {
  40. f = false;
  41. goto finish;
  42. }
  43. // make sure sscanf doesn't read past the end of the header, overwriting stack
  44. header[sizeof(header)-1]='\0';
  45. sscanf(header,"%s",solid);
  46. if(std::string("solid") == solid)
  47. {
  48. f = true;
  49. is_ascii = !perfect_size(stl_file);
  50. }else
  51. {
  52. is_ascii = false;
  53. f = perfect_size(stl_file);
  54. }
  55. finish:
  56. rewind(stl_file);
  57. return f;
  58. }
  59. IGL_INLINE bool igl::is_stl(FILE * stl_file)
  60. {
  61. bool is_ascii;
  62. return is_stl(stl_file,is_ascii);
  63. }