load_factory.h
1/***************************************************************************
2 *
3 * Copyright (C) 2007 by Willem van Straten
4 * Licensed under the Academic Free License version 2.1
5 *
6 ***************************************************************************/
7
8#include "Reference.h"
9#include "Error.h"
10#include "FilePtr.h"
11
12#include "strutil.h"
13#include "dirutil.h"
14
15#include <vector>
16
18
31
32template<class Parent>
33Parent* factory (FILE* fptr)
34{
35 long current = ftell (fptr);
36
37 std::vector< Reference::To<Parent> > candidates;
38
39 Parent::children (candidates);
40
41 for (unsigned i=0; i < candidates.size(); i++) {
42
43 if (fseek (fptr, current, SEEK_SET) < 0)
44 throw Error (FailedSys, "factory (FILE*)", "fseek");
45
46 try {
47 candidates[i]->load (fptr);
48 return candidates[i].release();
49 }
50 catch (Error& error) { }
51
52 }
53 throw Error (InvalidParam, "factory (FILE*)",
54 "no child recognizes contents of file");
55}
56
57template<class Parent>
58Parent* factory (FILE* fptr, size_t nbytes)
59{
60 FilePtr temp = tmpfile();
61 if (!temp)
62 throw Error (FailedSys, "factory (FILE*, size_t)", "tmpfile");
63
64 ::copy (fptr, temp, nbytes);
65
66 rewind (temp);
67 return factory<Parent> (temp);
68}
69
70template<class Parent>
71Parent* factory (const std::string& filename)
72{
73 std::string use_filename = expand (filename);
74
75 FilePtr temp = fopen (use_filename.c_str(), "r");
76 if (!temp)
77 throw Error (FailedSys, "factory (std::string&)",
78 "fopen (%s)", use_filename.c_str());
79
80 return factory<Parent> (temp);
81}
82
83//
84// the following functions are not really factories, but were inspired
85// by the ideas implemented above
86//
87template<class Any>
88Any* load (const std::string& filename)
89{
90 std::string use_filename = expand (filename);
91
92 FilePtr temp = fopen (use_filename.c_str(), "r");
93 if (!temp)
94 throw Error (FailedSys, "Any* load (std::string&)",
95 "fopen (%s)", use_filename.c_str());
96
97 Any* any = new Any;
98 any -> load (temp);
99 return any;
100}
101
102template<class Any>
103size_t nbytes (const Any* any)
104{
105 FilePtr temp = tmpfile();
106 if (!temp)
107 throw Error (FailedSys, "nbytes (Any*)", "tmpfile");
108
109 any->unload (temp);
110 return ftell (temp);
111}
A convenient exception handling class.
Definition Error.h:54
Closes a FILE* when it goes out of scope.
Definition FilePtr.h:19

Generated using doxygen 1.14.0