Repository navigation
Expand file tree
/
Copy pathFile.hpp
More file actions
408 lines (399 loc) · 10.5 KB
/
Copy pathFile.hpp
File metadata and controls
408 lines (399 loc) · 10.5 KB
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
#pragma once
#define PCL_FILE
#include<cstdio>
#include<ctime>
#include<string>
#include<format>
#include<filesystem>
#include<fstream>
#include<functional>
#include<array>
#include<cstddef>
using std::string;
using std::string_view;
#include"Exception.hpp"
#include"StrUtils.hpp"
#include"EnumLookup.hpp"
namespace fs=std::filesystem;
namespace pc{
namespace file{
const pc::Exceptioner xptFile("File");
enum class Mode{
Insert,Overwrite,Attach,
ReadOnly,OverwriteOnly,AttachOnly
};
EnumLookup<Mode,std::ios::openmode> ModeLookup{
Mode::Insert, std::ios::in|std::ios::out,
Mode::Overwrite, std::ios::in|std::ios::out|std::ios::trunc,
Mode::Attach, std::ios::in|std::ios::out|std::ios::app,
Mode::ReadOnly, std::ios::in,
Mode::OverwriteOnly,std::ios::out|std::ios::trunc,
Mode::AttachOnly, std::ios::out|std::ios::app
};
class File
{
protected:
std::fstream stream;
fs::path path;
std::ios::openmode openmode;
/// @brief guard unexpected read
void tryRead(){
if(!HasMode(std::ios::in))
xptFile.Throw(xpt::ACCESS_DENIED,
"Reading file '{}' which was opened in unreadable mode",
path.string()
);
}
/// @brief guard unexpected write
void tryWrite(){
if(!HasMode(std::ios::out))
xptFile.Throw(xpt::ACCESS_DENIED,
"Writing to file '{}' which was opened in readonly mode",
path.string()
);
}
public:
/// @brief Open a file
virtual void Open(Mode mode,fs::path filePath){
Open(ModeLookup(mode),filePath);
}
void Open(std::ios_base::openmode mode,fs::path filePath)
{
openmode=mode;
if(openmode&std::ios::in&&!openmode&std::ios::out&&!fs::exists(filePath))
xptFile.Throw(xpt::FILE_NOT_FOUND,
"No such a file '{}'",filePath.string());
stream.open(filePath,openmode);
path=filePath;
if(!stream.is_open())
xptFile.Throw(xpt::FILE,
"Fail to open file '{}' (errno: {})",
filePath.string(),std::to_string(errno)
);
}
/// @brief Close the file
void Close(){
if(!IsOpen()) return;
stream.flush();
stream.close();
}
/// @brief Default constructor with no file opened
File(){}
/// @brief Open a file with specified mode and path
File(Mode mode,fs::path filePath){
Open(mode,filePath);
}
/**
* @brief Open a file with specified mode and path
* @param fmt The format of the path, can be used with `std::format`
* @param args The arguments for the format
*/
template<typename ...Tps>
File(Mode mode,string_view fmt,Tps...args){
fs::path filePath;
string str;
try{
str=std::vformat(fmt,std::make_format_args(args...));
filePath=str;
}catch(...){
xptFile.Throw(xpt::INVALID_ARGUMENT,
"Invalid file path '{}'",str);
}
Open(mode,filePath);
}
~File(){Close();}
/// @brief Check if the file is opened
bool IsOpen(){return stream.is_open();}
/// @brief Check if reached end of file
bool Eof(){return stream.eof();}
/// @brief Sync with native device
void Flush(){stream.flush();}
/// @brief check if the file opened in this mode
bool HasMode(std::ios::openmode m){return m&openmode;}
};
/// @brief Text file operation class
class Text: public File
{
public:
using File::File;
/// @brief get a character from file
char GetChar(){
tryRead();
return stream.get();
}
/// @brief ignore chars in the stream
void Ignore(su::CharType shouldIgnore){
tryRead();
if(Eof()) return;
while(shouldIgnore(stream.peek()))
stream.get();
}
/// @brief ignore chars in the stream
inline void Ignore(std::string_view chars){
Ignore(su::Delimiters::List(chars));
}
/**
* @brief Get a token breaking with delimiter from file
* @param isDelimiter Decide whether the char is a delimiter
* @return the gotten token
* @note More `isDelimiter` decleration are in `su::Delimiters`
*/
string GetToken(su::CharType isDelimiter)
{
tryRead();
string ans;
Ignore(isDelimiter);
while(true){
if(Eof()) break;
char in=stream.get();
if(isDelimiter(in)) break;
else ans+=in;
}
return ans;
}
/// @brief Get a line
inline string GetWord(){
return GetToken(su::Delimiters::Word);
}
/// @brief Get a line
inline string GetLine(){
return GetToken(su::Delimiters::Line);
}
/// @brief Put char to file
void PutChar(char ch){
tryWrite();
stream.put(ch);
}
/// @brief Print to file with `std::format`
template<typename ...Tps>
void Print(std::string fmt,Tps ...args)
{
std::string res=std::vformat(fmt,std::make_format_args(args...));
stream<<res;
return;
}
private:
/// @brief Basic seek function
inline void seekReadBase(int offset,std::ios_base::seekdir mode){
tryRead();
stream.seekg(offset,mode);
}
inline void seekWriteBase(int offset,std::ios_base::seekdir mode){
tryWrite();
stream.seekp(offset,mode);
}
public:
/// @brief read cursor offset by `x`
inline void SeekReadCur(int x)
{seekReadBase(x,std::ios_base::cur);}
/// @brief read cursor goto position `x`
inline void SeekReadHome(int x)
{seekReadBase(std::abs(x),std::ios_base::cur);}
/// @brief read cursor goto `x` count from end
inline void SeekReadEnd(int x)
{seekReadBase(-std::abs(x),std::ios_base::end);}
/// @brief write cursor offset by `x`
inline void SeekWriteCur(int x)
{seekWriteBase(x,std::ios_base::cur);}
/// @brief write cursor goto position `x`
inline void SeekWriteHome(int x)
{seekWriteBase(std::abs(x),std::ios_base::cur);}
/// @brief write cursor goto `x` count from end
inline void SeekWriteEnd(int x)
{seekWriteBase(-std::abs(x),std::ios_base::end);}
/// @brief Get current read cursor position
inline int GetReadPos(){return stream.tellg();}
/// @brief Get current read cursor position
inline int GetWritePos(){return stream.tellp();}
/// @brief Get file content as string
std::string ReadAll()
{
tryRead();
SeekReadHome(0);
std::string ans;
char ch;
while(true)
{
ch=stream.get();
if(ch==-1||Eof())
break;
ans+=ch;
}
return ans;
}
/// @brief Write string to file
void WriteAll(std::string str){stream<<str;}
};
/**
* @brief Automatically add time stamp to output
* @note The format can be modified in `pcpri::LogStartFormat`
* and `pcpri::LogFormat`
*/
class Log: protected Text
{
protected:
time_t Ti;tm* T;
int Se,Mi,Ho,Da,Mo,Ye,We;
void timeLoc()
{
Ti=time(0);
T=localtime(&Ti);
Se=T->tm_sec,
Mi=T->tm_min,
Ho=T->tm_hour,
We=T->tm_wday,
Da=T->tm_mday,
Mo=T->tm_mon+1,
Ye=T->tm_year+1900;
return;
}
public:
/// @brief Enum type for level of the logs.
enum class Levels{Trace,Debug,Info,Warning,Error,Fatal};
protected:
inline static const EnumLookup<Levels,std::string> LevelLookup{
Levels::Trace, "Trace",
Levels::Debug, "Debug",
Levels::Info, "Info",
Levels::Warning, "Warning",
Levels::Error, "Error",
Levels::Fatal, "Fatal"
};
Levels level=Levels::Info;
public:
/**
* @brief Format of the log header, can be used with `std::format`
* @note index of the args are:
* ```
* 0 Year | 1 Month | 2 Day
* 3 Hour | 4 Minute | 5 Second
* 6 WeekDay
* ```
*/
string HeadFormat="New log started in {0:04}/{1:02}/{2:02} {3:02}:{4:02}:{5:02}\n";
/**
* @brief Format of the log line, can be used with `std::format`
* @note index of the args are:
* ```
* 0 Year | 1 Month | 2 Day
* 3 Hour | 4 Minute | 5 Second
* 6 WeekDay | 7 Type
* ```
*/
string LineFormat="{0:04}/{1:02}/{2:02} {3:02}:{4:02}:{5:02} [{7}]";
Log(){}
Log(fs::path filePath){
Open(Mode::AttachOnly,filePath);
}
/// @brief Open a log
void Open(Mode mode,fs::path filePath)
{
File::Open(mode,filePath);
timeLoc();
string head=std::vformat(HeadFormat,std::make_format_args(Ye,Mo,Da,Ho,Mi,Se));
stream<<head;
Flush();
}
void Close(){File::Close();}
bool IsOpen(){return File::IsOpen();}
void Flush(){File::Flush();}
~Log(){Close();}
/// @brief Log line print
template<typename...types>
void PrintLn(Levels logLevel,string format,types... args){
if(logLevel<level) return;
timeLoc();
Text::Print(LineFormat,Ye,Mo,Da,Ho,Mi,Se,We,LevelLookup(logLevel));
Text::Print(format,args...);
Text::PutChar('\n');
}
template<typename...types>
inline void Trace(string format,types... args)
{PrintLn(Levels::Trace,format,args...);}
template<typename...types>
inline void Debug(string format,types... args)
{PrintLn(Levels::Debug,format,args...);}
template<typename...types>
inline void Info(string format,types... args)
{PrintLn(Levels::Info,format,args...);}
template<typename...types>
inline void Warning(string format,types... args)
{PrintLn(Levels::Warning,format,args...);}
template<typename...types>
inline void Error(string format,types... args)
{PrintLn(Levels::Error,format,args...);}
template<typename...types>
inline void Fatal(string format,types... args)
{PrintLn(Levels::Fatal,format,args...);}
template<typename...types>
inline void Print(string format,types... args)
{Print(format,args...);}
void SetLevel(Levels logLevel){level=logLevel;}
Levels GetLevel(){return level;}
string GetLevelString(){return LevelLookup(level);}
};
class Binary: public File
{
public:
using File::File;
typedef std::vector<std::byte> Bytes;
void Open(const Mode mode,fs::path filePath){
File::Open(ModeLookup(mode)|std::ios::binary,filePath);
}
/**
* @brief Directly dump the memory of the data in to file.
* @warning The structure of data must be trivially copyable,
* or undefined actions will occured
*/
template<typename Tp>
void Dump(Tp& data){
tryWrite();
stream.write(reinterpret_cast<char*>(&data),sizeof(data));
}
/// @brief Write bytes
void Write(Bytes bytes){
tryWrite();
stream.write(reinterpret_cast<char*>(bytes.data()),bytes.size());
}
/// @brief Call serializer and write bytes
template<typename Tp>
void Write(Tp data,std::function<Bytes(Tp)> serializer){
static_assert(std::is_trivially_copyable_v<Tp>,
"Tp must be trivially copyable for Dump");
Write(serializer(data));
}
/// @brief Directly load memory from file
template<typename Tp>
Tp Load()
{
static_assert(std::is_trivially_copyable_v<Tp>,
"Tp must be trivially copyable for Load");
tryRead();
Tp data;
stream.read(reinterpret_cast<char*>(&data),sizeof(data));
if(stream.gcount()!=sizeof(data))
xptFile.Throw(xpt::FILE,
"Fail to load bin from file {}",path);
return data;
}
/// @brief Read bytes
Bytes Read(unsigned int count)
{
tryRead();
Bytes bytes;
bytes.resize(count);
stream.read(reinterpret_cast<char*>(bytes.data()),count);
if(stream.gcount()!=count)
xptFile.Throw(xpt::FILE,
"Fail to read bin from file {}",path.string());
return bytes;
}
template<typename Tp>
Tp Read(std::function<Tp(std::fstream&)> deserializer){
return deserializer(stream);
}
};
using LogLvs=Log::Levels;
};//namespace file
namespace fl=file;
};//namespace pc