Console Library 8.0.0
A header-only library that makes C++ simple
Loading...
Searching...
No Matches
file.h
Go to the documentation of this file.
1
10
11/*
12Copyright (c) 2026 MrXie1109
13
14Permission is hereby granted, free of charge, to any person obtaining a copy
15of this software and associated documentation files (the "Software"), to deal
16in the Software without restriction, including without limitation the rights
17to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18copies of the Software, and to permit persons to whom the Software is
19furnished to do so, subject to the following conditions:
20
21The above copyright notice and this permission notice shall be included in all
22copies or substantial portions of the Software.
23
24THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30SOFTWARE.
31*/
32
33#pragma once
34#include <cstdio>
35#include <fstream>
36#include <iostream>
37#include <iterator>
38#include <string>
39#include <type_traits>
40#include <vector>
41
42#include "../core/csexc.h"
43#include "../text/strpp.h"
44
45namespace console {
51 template <class CharT = char>
52 class BasicPath {
53 using string_type = std::basic_string<CharT>;
54
56
57 public:
58 using Bytes = std::vector<unsigned char>;
59
64 BasicPath(const CharT *str) : path(string_type(str)) {}
65
71#ifdef _WIN32
72 for (auto &ch : path) {
73 if (ch == static_cast<CharT>('/'))
74 ch = static_cast<CharT>('\\');
75 }
76#endif
77 }
78
85 friend BasicPath operator/(const BasicPath &p1, const BasicPath &p2) {
86 return BasicPath(p1.path + static_cast<CharT>('/') + p2.path);
87 }
88
95 *this = *this / p;
96 return *this;
97 }
98
99 private:
104 std::string narrow() const {
105 return std::string(path.begin(), path.end());
106 }
107
113 template <class T = CharT>
114 static typename std::enable_if<std::is_same<T, char>::value,
115 string_type>::type
116 widen_or_pass(const std::string &s) {
117 return s;
118 }
119
125 template <class T = CharT>
126 static typename std::enable_if<std::is_same<T, wchar_t>::value,
127 string_type>::type
128 widen_or_pass(const std::string &s) {
129 return string_type(s.begin(), s.end());
130 }
131
137 template <class T = CharT>
138 static typename std::enable_if<std::is_same<T, char>::value, void>::type
139 write_to_stream(std::ofstream &fout, const string_type &text) {
140 fout << text;
141 }
142
148 template <class T = CharT>
149 static
150 typename std::enable_if<std::is_same<T, wchar_t>::value, void>::type
151 write_to_stream(std::ofstream &fout, const string_type &text) {
152 fout << std::string(text.begin(), text.end());
153 }
154
155 public:
161 std::ifstream fin(narrow());
162 if (!fin.is_open())
163 throw FileError("Cannot Open File \"" + narrow() + '"');
164 std::string buf{std::istreambuf_iterator<char>(fin),
165 std::istreambuf_iterator<char>()};
166 if (fin.fail() && !fin.eof())
167 throw FileError(
168 "The Stream of \"" + narrow() + "\" is Not Good");
169 return widen_or_pass(buf);
170 }
171
177 std::ifstream fin(narrow(), std::ios::binary);
178 if (!fin.is_open())
179 throw FileError("Cannot Open File \"" + narrow() + '"');
180 Bytes bytes{std::istreambuf_iterator<char>(fin),
181 std::istreambuf_iterator<char>()};
182 if (fin.fail() && !fin.eof())
183 throw FileError(
184 "The Stream of \"" + narrow() + "\" is Not Good");
185 return bytes;
186 }
187
192 std::vector<string_type> read_lines() const {
193 string_type text = read_text();
194 if (text.empty()) return {};
195 return split(text, string_type(1, static_cast<CharT>('\n')));
196 }
197
202 template <class T>
203 T read_POD() const {
204 static_assert(std::is_trivially_copyable<T>::value,
205 "This Type is Not POD Type!");
206 std::ifstream fin(narrow(), std::ios::binary);
207 if (!fin.is_open())
208 throw FileError("Cannot Open File \"" + narrow() + '"');
209 T data;
210 fin.read((char *)(&data), sizeof(data));
211 if (!fin.good())
212 throw FileError(
213 "The Stream of \"" + narrow() + "\" is Not Good");
214 return data;
215 }
216
221 template <class T>
223 std::ifstream fin(narrow(), std::ios::binary);
224 if (!fin.is_open())
225 throw FileError("Cannot Open File \"" + narrow() + '"');
226 T data;
227 fin.read((char *)(&data), sizeof(data));
228 if (!fin.good())
229 throw FileError(
230 "The Stream of \"" + narrow() + "\" is Not Good");
231 return data;
232 }
233
238 void write_text(const string_type &text) const {
239 std::ofstream fout(narrow());
240 if (!fout.is_open())
241 throw FileError("Cannot Open File \"" + narrow() + '"');
242 write_to_stream(fout, text);
243 if (fout.fail())
244 throw FileError(
245 "The Stream of \"" + narrow() + "\" is Not Good");
246 }
247
252 void write_binary(const Bytes &bts) const {
253 std::ofstream fout(narrow(), std::ios::binary);
254 if (!fout.is_open())
255 throw FileError("Cannot Open File \"" + narrow() + '"');
256 fout.write((const char *)(bts.data()), bts.size());
257 if (fout.fail())
258 throw FileError(
259 "The Stream of \"" + narrow() + "\" is Not Good");
260 }
261
266 void write_lines(const std::vector<string_type> &lines) const {
267 std::ofstream fout(narrow(), std::ios::binary);
268 if (lines.empty()) return;
269 if (!fout.is_open())
270 throw FileError("Cannot Open File \"" + narrow() + '"');
271 write_to_stream(fout, lines[0]);
272 for (size_t i = 1; i < lines.size(); ++i) {
273 fout << '\n';
274 write_to_stream(fout, lines[i]);
275 }
276 if (fout.fail())
277 throw FileError(
278 "The Stream of \"" + narrow() + "\" is Not Good");
279 }
280
285 template <class T>
286 void write_POD(const T &data) const {
287 static_assert(std::is_trivially_copyable<T>::value,
288 "This Type is Not POD Type!");
289 std::ofstream fout(narrow(), std::ios::binary);
290 if (!fout.is_open())
291 throw FileError("Cannot Open File \"" + narrow() + '"');
292 fout.write((const char *)(&data), sizeof(data));
293 if (fout.fail())
294 throw FileError(
295 "The Stream of \"" + narrow() + "\" is Not Good");
296 }
297
302 template <class T>
303 void unsafe_write_POD(const T &data) const {
304 std::ofstream fout(narrow(), std::ios::binary);
305 if (!fout.is_open())
306 throw FileError("Cannot Open File \"" + narrow() + '"');
307 fout.write((const char *)(&data), sizeof(data));
308 if (fout.fail())
309 throw FileError(
310 "The Stream of \"" + narrow() + "\" is Not Good");
311 }
312
318 bool exists() const { return std::ifstream{narrow()}.is_open(); }
319
324 void touch() const { std::ofstream{narrow()}; }
325
330 void ensure() const { std::ofstream{narrow(), std::ios::app}; }
331
335 void remove() const {
336 if (std::remove(narrow().c_str()) != 0)
337 throw FileError("Cannot Remove File \"" + narrow() + '"');
338 }
339
343 const string_type &str() const { return path; }
344
350 std::fstream stream(std::ios_base::openmode mode
351 = std::ios_base::in | std::ios_base::out) const {
352 return std::fstream(narrow(), mode);
353 }
354 };
355
360}
文件路径封装类,提供便捷的文件读写和路径操作。
Definition file.h:52
static std::enable_if< std::is_same< T, wchar_t >::value, void >::type write_to_stream(std::ofstream &fout, const string_type &text)
根据字符类型选择宽字符或窄字符转换函数。
Definition file.h:151
void write_binary(const Bytes &bts) const
写入二进制内容。
Definition file.h:252
string_type read_text() const
读取文本文件内容。
Definition file.h:160
void unsafe_write_POD(const T &data) const
写入 POD 类型数据(不安全)。
Definition file.h:303
bool exists() const
判断文件是否存在。
Definition file.h:318
static std::enable_if< std::is_same< T, char >::value, void >::type write_to_stream(std::ofstream &fout, const string_type &text)
根据字符类型选择宽字符或窄字符转换函数。
Definition file.h:139
friend BasicPath operator/(const BasicPath &p1, const BasicPath &p2)
重载运算符,用于路径拼接。
Definition file.h:85
void write_POD(const T &data) const
写入 POD 类型数据。
Definition file.h:286
static std::enable_if< std::is_same< T, wchar_t >::value, string_type >::type widen_or_pass(const std::string &s)
根据字符类型选择宽字符或窄字符转换函数。
Definition file.h:128
void remove() const
删除文件(若存在)。
Definition file.h:335
std::vector< string_type > read_lines() const
读取文本文件的行内容。
Definition file.h:192
void touch() const
创建文件(若不存在)。
Definition file.h:324
std::vector< unsigned char > Bytes
字节向量类型
Definition file.h:58
BasicPath(const string_type &str)
构造函数,接受一个字符串作为路径字符串。
Definition file.h:70
std::basic_string< CharT > string_type
字符串类型
Definition file.h:53
Bytes read_binary() const
读取二进制文件内容。
Definition file.h:176
static std::enable_if< std::is_same< T, char >::value, string_type >::type widen_or_pass(const std::string &s)
根据字符类型选择宽字符或窄字符转换函数。
Definition file.h:116
std::string narrow() const
将宽字符路径转换为窄字符路径。
Definition file.h:104
void write_text(const string_type &text) const
写入文本内容。
Definition file.h:238
T unsafe_read_POD() const
读取 POD 类型数据(不安全)。
Definition file.h:222
void write_lines(const std::vector< string_type > &lines) const
写入行内容。
Definition file.h:266
T read_POD() const
读取 POD 类型数据。
Definition file.h:203
std::fstream stream(std::ios_base::openmode mode=std::ios_base::in|std::ios_base::out) const
以指定模式打开文件流。
Definition file.h:350
void ensure() const
确保文件存在(若不存在则创建)。
Definition file.h:330
const string_type & str() const
Definition file.h:343
string_type path
Definition file.h:55
BasicPath & operator/=(const BasicPath &p)
重载运算符,用于路径拼接。
Definition file.h:94
BasicPath(const CharT *str)
构造函数,接受一个字符指针作为路径字符串。
Definition file.h:64
FileError(const std::string &msg)
构造 FileError。
Definition csexc.h:87
定义 console 库使用的自定义异常类层次结构。
std::vector< std::basic_string< CharT, Traits, Allocator > > split(const std::basic_string< CharT, Traits, Allocator > &text, const std::basic_string< CharT, Traits, Allocator > &sep=std::basic_string< CharT, Traits, Allocator >(1, CharT{' '}))
以分隔符分割字符串(类似 Python 的 split,默认按空格分割)。
Definition strpp.h:324
本库所有组件所在的顶层命名空间。
@ T
Definition kb.h:99
BasicPath< char > Path
窄字符路径类型。
Definition file.h:357
BasicPath< wchar_t > WPath
宽字符路径类型。
Definition file.h:359
提供字符串处理工具函数和格式化类。