Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
BinaryFileReader.h
Go to the documentation of this file.
1/* This file is part of MoDELib, the Mechanics Of Defects Evolution Library.
2 *
3 *
4 * MoDELib is distributed without any warranty under the
5 * GNU General Public License (GPL) v2 <http://www.gnu.org/licenses/>.
6 */
7
8#ifndef model_BINARYFILEREADER_H_
9#define model_BINARYFILEREADER_H_
10
11#include <iostream>
12#include <fstream>
13#include <string>
14#include <assert.h>
15#include <vector>
16#include <cmath>
17
18namespace model
19{
20
28 template <typename DataType>
29 class BinaryFileReader : public std::vector<DataType>
30 {
31
32 static constexpr size_t _bytes_in_Type=sizeof (DataType);
33
34
35 std::ifstream::pos_type _bytes_in_file;
36 bool _success;
37
38 public:
39
40 BinaryFileReader(const std::string& filename) :
41 /* init list */ _bytes_in_file(0)
42 /* init list */,_success(false)
43 {
47
48// this->clear();
49
50 // open file with the ios::ate flag in order to set the get pointer at the end of the file.
51 std::ifstream file (filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
52
53 if (file.is_open())
54 {
55
56 // Since the get pointer is at the end of the file, call file.tellg() to obtain the number of bytes in the file
57 _bytes_in_file = file.tellg();
58
59 // The number of bytes in the file must be a multiple of the number of bytes in Type
60 assert((_bytes_in_file%_bytes_in_Type)==0 && " Incorrect format.");
61
62 // Calculate how many element of type Type are in the file
63 const size_t _array_size = _bytes_in_file/_bytes_in_Type;
64 this->resize(_array_size);
65
66 // resize memblock with _array_size
67
68 // bring back the get pointer to the beginning of the file
69 file.seekg (0, std::ios::beg);
70
71 // read the file into memblock
72 file.read (reinterpret_cast<char*>(this->data()), _bytes_in_file);
73
74 // close the file
75 file.close();
76
77 _success=true;
78 }
79 else
80 {
81 std::cout << "Unable to open file "<<filename<<std::endl;
82 }
83
84 }
85
86 size_t bytes() const
87 {
89 return _bytes_in_file;
90 }
91
92 const bool& success() const
93 {
95 return _success;
96 }
97
98 };
99
100} // namespace model
101#endif
BinaryFileReader(const std::string &filename)
const bool & success() const