DISPLACE  1.0
A spatial model of fisheries to help sustainable fishing and maritime spatial planning
binarygraphfilewriter.h
Go to the documentation of this file.
1 #ifndef BINARYGRAPHFILEWRITER_H
2 #define BINARYGRAPHFILEWRITER_H
3 
4 #include <formats_globals.h>
5 
6 #include <utils/endian.h>
7 
8 #include <string>
9 #include <functional>
10 
11 #include <cstdio>
12 
13 #include <system_error>
14 
15 #ifdef _MSC_VER
16 #define PACKED
17 #else
18 #define PACKED __attribute__ ((__packed__))
19 #endif
20 
21 namespace displace {
22 namespace formats {
23 namespace legacy {
24 
25 using namespace displace::formats::helpers;
26 
27 template <typename Key, typename Value>
29 
30  FILE *mFile = nullptr;
31 public:
33  }
34 
35  bool open (const std::string &filename) {
36  mFile = fopen(filename.c_str(), "wb");
37  if (mFile == nullptr) {
38  throw std::system_error(errno,std::generic_category());
39  }
40 
41  #pragma pack(push,1)
42  struct PACKED {
43  uint32_t signature;
44  uint8_t keysize, valuesize;
45  } header;
46  #pragma pack(pop)
47 
48  header.signature = toLittleEndian((uint32_t)0x01020304);
49  header.keysize = sizeof(Key);
50  header.valuesize = sizeof(Value);
51 
52  if (fwrite(&header, sizeof(header), 1, mFile) != 1) {
53  throw std::system_error(errno,std::generic_category());
54  }
55  return true;
56  }
57 
58  bool write (Key key, Value value) {
59  #pragma pack(push,1)
60  struct PACKED {
61  Key k;
62  Value v;
63  } rec;
64  #pragma pack(pop)
65 
66  rec.k = toLittleEndian(key);
67  rec.v = toLittleEndian(value);
68 
69  if (fwrite(&rec, sizeof(rec), 1, mFile ) != 1) {
70  throw std::system_error(errno,std::generic_category());
71  }
72  return true;
73  }
74 
75  bool close() {
76  fclose(mFile);
77  return true;
78  }
79 };
80 
81 } // ns
82 }
83 }
84 
85 
86 #endif // BINARYGRAPHFILEWRITER_H
#define PACKED
Definition: binarygraphfilewriter.h:18
Definition: decisiontreemanager.h:13
bool write(Key key, Value value)
Definition: binarygraphfilewriter.h:58
BinaryGraphFileWriter()
Definition: binarygraphfilewriter.h:32
Definition: binarygraphfilewriter.h:28
std::pair< box, unsigned > value
Definition: diffusion.cpp:30
Definition: endian.h:10
bool close()
Definition: binarygraphfilewriter.h:75
bool open(const std::string &filename)
Definition: binarygraphfilewriter.h:35
uint16_t toLittleEndian(uint16_t v)
Definition: endian.h:55