PSCF v1.5.0
TextFileIArchive.cpp
1/*
2* Util Package - C++ Utilities for Scientific Computation
3*
4* Copyright 2010 - 2017, David Morse (morse012@um.edu)
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#include "TextFileIArchive.h"
9
10#include <vector>
11
12namespace Util
13{
14
15 /*
16 * Constructor.
17 */
19 : filePtr_(0),
20 version_(0),
21 createdFile_(true)
22 { filePtr_ = new std::ifstream(); }
23
24 /*
25 * Constructor.
26 */
28 : filePtr_(0),
29 version_(0),
30 createdFile_(true)
31 { filePtr_ = new std::ifstream(filename.c_str()); }
32
33
34 /*
35 * Constructor.
36 */
38 : filePtr_(&file),
39 version_(0),
40 createdFile_(false)
41 {
42 if (!file.is_open()) {
43 UTIL_THROW("File not open");
44 }
45 }
46
47
48 /*
49 * Destructor.
50 */
52 {
53 if (filePtr_ && createdFile_) {
54 delete filePtr_;
55 }
56 }
57
58 /*
59 * Return underlying file by reference.
60 */
61 std::ifstream& TextFileIArchive::file()
62 { return *filePtr_; }
63
64 /*
65 * Read trailing whitespace and the newline at the end of a record.
66 */
68 {
69 if (!filePtr_->good()) return;
70 int c = filePtr_->peek();
71 while (c == ' ' || c == '\t' || c == '\r') {
72 filePtr_->get();
73 c = filePtr_->peek();
74 }
75 if (c == '\n') {
76 filePtr_->get();
77 }
78 }
79
80 /*
81 * Load a std::string from TextFileIArchive.
82 */
83 template <>
84 void serialize(TextFileIArchive& ar, std::string& data,
85 const unsigned int version)
86 {
87 size_t size;
88 ar.unpack(size);
89 if (size > 0) {
90 // Read size characters, including any whitespace
91 data.resize(size);
92 ar.file().read(&data[0], size);
93 ar.endRecord();
94 } else {
95 data = "";
96 }
97 }
98
99}
Loading archive for text istream.
void endRecord()
Read the end of a record written by TextFileOArchive::pack().
std::ifstream & file()
Get the underlying ifstream by reference.
void unpack(T &data)
Load a single T object.
virtual ~TextFileIArchive()
Destructor.
Utility classes for scientific computation.