Open Chinese Convert 1.1.9
A project for conversion between Traditional and Simplified Chinese
Loading...
Searching...
No Matches
SerializableDict.hpp
1/*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2014 Carbo Kuo <byvoid@byvoid.com>
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19#pragma once
20
21#include "Dict.hpp"
22
23namespace opencc {
28class OPENCC_EXPORT SerializableDict {
29public:
33 virtual void SerializeToFile(FILE* fp) const = 0;
34
38 virtual void SerializeToFile(const std::string& fileName) const {
39 FILE* fp = fopen(fileName.c_str(), "wb");
40 if (fp == NULL) {
41 throw FileNotWritable(fileName);
42 }
43 SerializeToFile(fp);
44 fclose(fp);
45 }
46
47 template <typename DICT>
48 static bool TryLoadFromFile(const std::string& fileName,
49 std::shared_ptr<DICT>* dict) {
50 FILE* fp =
51#ifdef _MSC_VER
52 // well, the 'GetPlatformString' shall return a 'wstring'
53 _wfopen(UTF8Util::GetPlatformString(fileName).c_str(), L"rb")
54#else
55 fopen(UTF8Util::GetPlatformString(fileName).c_str(), "rb")
56#endif // _MSC_VER
57 ;
58
59 if (fp == NULL) {
60 return false;
61 }
62 std::shared_ptr<DICT> loadedDict = DICT::NewFromFile(fp);
63 fclose(fp);
64 *dict = loadedDict;
65 return true;
66 }
67
68 template <typename DICT>
69 static std::shared_ptr<DICT> NewFromFile(const std::string& fileName) {
70 std::shared_ptr<DICT> dict;
71 if (!TryLoadFromFile<DICT>(fileName, &dict)) {
72 throw FileNotFound(fileName);
73 }
74 return dict;
75 }
76};
77} // namespace opencc
Definition Exception.hpp:55
Serializable dictionary interface.
Definition SerializableDict.hpp:28
virtual void SerializeToFile(const std::string &fileName) const
Serializes the dictionary and writes in to a file.
Definition SerializableDict.hpp:38
virtual void SerializeToFile(FILE *fp) const =0
Serializes the dictionary and writes in to a file.