diff --git a/dune/gmsh4/utility/version.hh b/dune/gmsh4/utility/version.hh new file mode 100644 index 0000000000000000000000000000000000000000..7599e2b6df9bf996ffea7d04ec66f02cba7d7d85 --- /dev/null +++ b/dune/gmsh4/utility/version.hh @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include "string.hh" + +namespace Dune +{ + namespace Gmsh4 + { + /// Return a version tuple identifying the .msh file format version + inline std::vector fileVersion(std::string filename) + { + std::ifstream file(filename, std::ios_base::in); + std::string section; + file >> section; + + if (section != "$MeshFormat") + DUNE_THROW(Dune::IOError, "Invalid header of msh file."); + + std::string version; + int file_type = -1; + int data_size = -1; + file >> version >> file_type >> data_size; + + if (std::stod(version) <= 0.0) + DUNE_THROW(Dune::IOError, "Invalid version number in msh file."); + + if (file_type != 0 and file_type != 1) + DUNE_THROW(Dune::IOError, "Invalid file-type: 0 for ASCII mode, 1 for binary mode."); + + if (data_size < 4 || data_size > 16) + DUNE_THROW(Dune::IOError, "Invalid data-size range: should be in {4, 16}"); + + std::vector version_tuple; + split(version.begin(), version.end(), '.', [&](auto first, auto last) { + version_tuple.push_back(std::stoi(std::string{first,last})); + }); + + return version_tuple; + } + } +} diff --git a/src/gmsh4reader.cc b/src/gmsh4reader.cc index 3d97f92943a04ef5937bdb9c3ca434ea8e2900d3..8597753bfed5612114a67625b45b789b87e98bf7 100644 --- a/src/gmsh4reader.cc +++ b/src/gmsh4reader.cc @@ -19,6 +19,7 @@ #include #include #include +#include #include @@ -34,6 +35,10 @@ int main(int argc, char** argv) using GridType = Dune::ALUGrid<2,2,Dune::simplex,Dune::conforming>; using GridView = typename GridType::LeafGridView; { + auto ver = Gmsh4::fileVersion(GRID_PATH "/square.msh"); + if (ver[0] != 4) + DUNE_THROW(Dune::Exception, "Wrong .msh file version"); + auto gridPtr = Gmsh4Reader::createGridFromFile(GRID_PATH "/square.msh"); auto& grid = *gridPtr; @@ -50,6 +55,10 @@ int main(int argc, char** argv) } { + auto ver = Gmsh4::fileVersion(GRID_PATH "/square_part2.msh"); + if (ver[0] != 4) + DUNE_THROW(Dune::Exception, "Wrong .msh file version"); + auto gridPtr = Gmsh4Reader::createGridFromFile(GRID_PATH "/square_part2.msh"); auto& grid = *gridPtr;