forked from graphitemaster/neothyne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
u_file.h
109 lines (84 loc) · 2.31 KB
/
u_file.h
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
#ifndef U_FILE_HDR
#define U_FILE_HDR
#include <stdio.h>
#include "u_optional.h"
#include "u_string.h"
#include "u_vector.h"
namespace u {
#ifdef _WIN32
static constexpr char kPathSep = '\\';
#else
static constexpr char kPathSep = '/';
#endif
// A little unique_ptr like file wrapper to achieve RAII. We can't use
// unique_ptr here because unique_ptr doesn't allow null default delters
struct file {
file();
file(FILE *fp);
~file();
operator FILE*();
FILE *get();
private:
FILE *m_handle;
};
u::string fixPath(const u::string &path);
enum pathType {
kFile,
kDirectory
};
struct dir {
struct const_iterator {
const_iterator(void *handle);
const_iterator& operator++();
const char *operator*() const;
friend bool operator !=(const const_iterator &a, const const_iterator &);
private:
void *m_handle;
const char *m_name;
};
dir(const u::string &where);
dir(const char *where);
~dir();
const_iterator begin() const;
const_iterator end() const;
static bool isFile(const char *fileName);
static bool isFile(const u::string &fileName);
private:
void *m_handle;
};
// check if a file or directory exists
bool exists(const u::string &path, pathType type = kFile);
// remove a file or directory
bool remove(const u::string &file, pathType type = kFile);
// open a file
u::file fopen(const u::string& infile, const char *type);
// read file line by line
u::optional<u::string> getline(u::file &fp);
// read a file into vector
u::optional<u::vector<unsigned char>> read(const u::string &file, const char *mode = "rb");
// write a vector to file
bool write(const u::vector<unsigned char> &data, const u::string &file, const char *mode = "wb");
// make a directory
bool mkdir(const u::string &dir);
///! dir
inline dir::dir(const u::string &where)
: dir(where.c_str())
{
}
inline const char *dir::const_iterator::operator*() const {
return m_name ? m_name : "";
}
inline bool operator !=(const dir::const_iterator &a, const dir::const_iterator &) {
return a.m_name;
}
inline dir::const_iterator dir::begin() const {
return { m_handle };
}
inline dir::const_iterator dir::end() const {
return { nullptr };
}
inline bool dir::isFile(const u::string &fileName) {
return dir::isFile(fileName.c_str());
}
}
#endif