-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathascii_file.cpp
122 lines (93 loc) · 2.54 KB
/
ascii_file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "ascii_file.h"
#include <cstring>
#include <errno.h>
#include <stdarg.h>
#include <cstdlib>
AsciiFile::AsciiFile(const char comment_symbol): ifstream(), CommentSymbol(comment_symbol)
{
}
AsciiFile::AsciiFile(const char* filename, const char comment_symbol):
ifstream(filename), CommentSymbol(comment_symbol)
{
// open(filename);
}
//void AsciiFile::Open(const char *filename)
//{
// fst.open(filename);
// if ( !fst ) {
// throw bad_ascii_file(AsciiFile::OpenFailure);
// }
//}
AsciiFile::AsciiFileFlag AsciiFile::ReadLine(size_t N_elems, ...)
{
char s[MAX_STR_LEN];
char *subs, *start, *end;
double val,*pval;
size_t i;
// fst.getline(s,MAX_STR_LEN);
// if ( fst.eof() ) return AsciiFile::Eof;
getline(s,MAX_STR_LEN);
if ( eof() ) return AsciiFile::Eof;
// delete leading spaces
for (i = 0; i < MAX_STR_LEN; ++i ) {
if ( s[i] != ' ' ) break;
}
if ( i == strlen(s) ) return AsciiFile::EmptyString;
// subs = strndup(s+i,MAX_STR_LEN-i);
subs = strdup(s+i);
if ( errno == ENOMEM ) throw bad_alloc();
if ( subs[0] == CommentSymbol ) return AsciiFile::CommentString;
va_list args;
va_start(args, N_elems);
start = subs;
for (i = 0; i < N_elems; ++i ) {
val = strtod(start,&end);
if ( end != start ) {
pval = va_arg(args,double*);
*pval = val;
} else break;
start = end;
}
free(subs);
va_end(args);
if ( i != N_elems ) {
return AsciiFile::InvalidData;
}
return AsciiFile::DataString;
}
AsciiFile::AsciiFileFlag AsciiFile::ReadLine(size_t N_elems, vector<double> *data)
{
char s[MAX_STR_LEN];
char *subs, *start, *end;
double val,*pval;
size_t i;
getline(s,MAX_STR_LEN);
if ( eof() ) return AsciiFile::Eof;
// delete leading spaces
for (i = 0; i < MAX_STR_LEN; ++i ) {
if ( s[i] != ' ' ) break;
}
if ( i == strlen(s) ) return AsciiFile::EmptyString;
subs = strdup(s+i);
// subs = strndup(s+i,MAX_STR_LEN-i);
if ( errno == ENOMEM ) throw bad_alloc();
if ( subs[0] == CommentSymbol ) return AsciiFile::CommentString;
data->clear();
start = subs;
for (i = 0; i < N_elems; ++i ) {
val = strtod(start,&end);
if ( end != start ) {
data->push_back(val);
} else break;
start = end;
}
free(subs);
if ( i != N_elems ) {
return AsciiFile::InvalidData;
}
return AsciiFile::DataString;
}
//void AsciiFile::Close()
//{
// fst.close();
//}