1 // Formatting library for C++ - optional OS-specific functionality
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
6 // For the license information refer to format.h.
17 # include <system_error> // std::system_error
19 # if FMT_HAS_INCLUDE(<xlocale.h>)
20 # include <xlocale.h> // LC_NUMERIC_MASK on macOS
25 // UWP doesn't provide _pipe.
26 # if FMT_HAS_INCLUDE("winapifamily.h")
27 # include <winapifamily.h>
29 # if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
30 defined(__linux__)) && \
31 (!defined(WINAPI_FAMILY) || \
32 (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
33 # include <fcntl.h> // for O_RDONLY
34 # define FMT_USE_FCNTL 1
36 # define FMT_USE_FCNTL 0
41 # if defined(_WIN32) && !defined(__MINGW32__)
42 // Fix warnings about deprecated symbols.
43 # define FMT_POSIX(call) _##call
45 # define FMT_POSIX(call) call
49 // Calls to system functions are wrapped in FMT_SYSTEM for testability.
51 # define FMT_HAS_SYSTEM
52 # define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
54 # define FMT_SYSTEM(call) ::call
56 // Fix warnings about deprecated symbols.
57 # define FMT_POSIX_CALL(call) ::_##call
59 # define FMT_POSIX_CALL(call) ::call
63 // Retries the expression while it evaluates to error_result and errno
66 # define FMT_RETRY_VAL(result, expression, error_result) \
68 (result) = (expression); \
69 } while ((result) == (error_result) && errno == EINTR)
71 # define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
74 #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
80 * A reference to a null-terminated string. It can be constructed from a C
81 * string or `std::string`.
83 * You can use one of the following type aliases for common character types:
85 * +---------------+-----------------------------+
86 * | Type | Definition |
87 * +===============+=============================+
88 * | cstring_view | basic_cstring_view<char> |
89 * +---------------+-----------------------------+
90 * | wcstring_view | basic_cstring_view<wchar_t> |
91 * +---------------+-----------------------------+
93 * This class is most useful as a parameter type for functions that wrap C APIs.
95 template <typename Char
> class basic_cstring_view
{
100 /// Constructs a string reference object from a C string.
101 basic_cstring_view(const Char
* s
) : data_(s
) {}
103 /// Constructs a string reference from an `std::string` object.
104 basic_cstring_view(const std::basic_string
<Char
>& s
) : data_(s
.c_str()) {}
106 /// Returns the pointer to a C string.
107 auto c_str() const -> const Char
* { return data_
; }
110 using cstring_view
= basic_cstring_view
<char>;
111 using wcstring_view
= basic_cstring_view
<wchar_t>;
114 FMT_API
const std::error_category
& system_category() noexcept
;
117 FMT_API
void format_windows_error(buffer
<char>& out
, int error_code
,
118 const char* message
) noexcept
;
121 FMT_API
std::system_error
vwindows_error(int error_code
, string_view format_str
,
125 * Constructs a `std::system_error` object with the description of the form
127 * <message>: <system-message>
129 * where `<message>` is the formatted message and `<system-message>` is the
130 * system message corresponding to the error code.
131 * `error_code` is a Windows error code as given by `GetLastError`.
132 * If `error_code` is not a valid error code such as -1, the system message
133 * will look like "error -1".
137 * // This throws a system_error with the description
138 * // cannot open file 'madeup': The system cannot find the file
140 * // or similar (system message may vary).
141 * const char *filename = "madeup";
142 * LPOFSTRUCT of = LPOFSTRUCT();
143 * HFILE file = OpenFile(filename, &of, OF_READ);
144 * if (file == HFILE_ERROR) {
145 * throw fmt::windows_error(GetLastError(),
146 * "cannot open file '{}'", filename);
149 template <typename
... Args
>
150 std::system_error
windows_error(int error_code
, string_view message
,
151 const Args
&... args
) {
152 return vwindows_error(error_code
, message
, fmt::make_format_args(args
...));
155 // Reports a Windows error without throwing an exception.
156 // Can be used to report errors from destructors.
157 FMT_API
void report_windows_error(int error_code
, const char* message
) noexcept
;
159 inline auto system_category() noexcept
-> const std::error_category
& {
160 return std::system_category();
164 // std::system is not available on some platforms such as iOS (#2248).
166 template <typename S
, typename
... Args
, typename Char
= char_t
<S
>>
167 void say(const S
& format_str
, Args
&&... args
) {
168 std::system(format("say \"{}\"", format(format_str
, args
...)).c_str());
173 class buffered_file
{
179 explicit buffered_file(FILE* f
) : file_(f
) {}
182 buffered_file(const buffered_file
&) = delete;
183 void operator=(const buffered_file
&) = delete;
185 // Constructs a buffered_file object which doesn't represent any file.
186 buffered_file() noexcept
: file_(nullptr) {}
188 // Destroys the object closing the file it represents if any.
189 FMT_API
~buffered_file() noexcept
;
192 buffered_file(buffered_file
&& other
) noexcept
: file_(other
.file_
) {
193 other
.file_
= nullptr;
196 auto operator=(buffered_file
&& other
) -> buffered_file
& {
199 other
.file_
= nullptr;
204 FMT_API
buffered_file(cstring_view filename
, cstring_view mode
);
207 FMT_API
void close();
209 // Returns the pointer to a FILE object representing this file.
210 auto get() const noexcept
-> FILE* { return file_
; }
212 FMT_API
auto descriptor() const -> int;
214 template <typename
... T
>
215 inline void print(string_view fmt
, const T
&... args
) {
216 const auto& vargs
= fmt::make_format_args(args
...);
217 detail::is_locking
<T
...>() ? fmt::vprint_buffered(file_
, fmt
, vargs
)
218 : fmt::vprint(file_
, fmt
, vargs
);
224 // A file. Closed file is represented by a file object with descriptor -1.
225 // Methods that are not declared with noexcept may throw
226 // fmt::system_error in case of failure. Note that some errors such as
227 // closing the file multiple times will cause a crash on Windows rather
228 // than an exception. You can get standard behavior by overriding the
229 // invalid parameter handler with _set_invalid_parameter_handler.
232 int fd_
; // File descriptor.
234 // Constructs a file object with a given descriptor.
235 explicit file(int fd
) : fd_(fd
) {}
240 // Possible values for the oflag argument to the constructor.
242 RDONLY
= FMT_POSIX(O_RDONLY
), // Open for reading only.
243 WRONLY
= FMT_POSIX(O_WRONLY
), // Open for writing only.
244 RDWR
= FMT_POSIX(O_RDWR
), // Open for reading and writing.
245 CREATE
= FMT_POSIX(O_CREAT
), // Create if the file doesn't exist.
246 APPEND
= FMT_POSIX(O_APPEND
), // Open in append mode.
247 TRUNC
= FMT_POSIX(O_TRUNC
) // Truncate the content of the file.
250 // Constructs a file object which doesn't represent any file.
251 file() noexcept
: fd_(-1) {}
253 // Opens a file and constructs a file object representing this file.
254 file(cstring_view path
, int oflag
);
257 file(const file
&) = delete;
258 void operator=(const file
&) = delete;
260 file(file
&& other
) noexcept
: fd_(other
.fd_
) { other
.fd_
= -1; }
262 // Move assignment is not noexcept because close may throw.
263 auto operator=(file
&& other
) -> file
& {
270 // Destroys the object closing the file it represents if any.
273 // Returns the file descriptor.
274 auto descriptor() const noexcept
-> int { return fd_
; }
279 // Returns the file size. The size has signed type for consistency with
281 auto size() const -> long long;
283 // Attempts to read count bytes from the file into the specified buffer.
284 auto read(void* buffer
, size_t count
) -> size_t;
286 // Attempts to write count bytes from the specified buffer to the file.
287 auto write(const void* buffer
, size_t count
) -> size_t;
289 // Duplicates a file descriptor with the dup function and returns
290 // the duplicate as a file object.
291 static auto dup(int fd
) -> file
;
293 // Makes fd be the copy of this file descriptor, closing fd first if
297 // Makes fd be the copy of this file descriptor, closing fd first if
299 void dup2(int fd
, std::error_code
& ec
) noexcept
;
301 // Creates a buffered_file object associated with this file and detaches
302 // this file object from the file.
303 auto fdopen(const char* mode
) -> buffered_file
;
305 # if defined(_WIN32) && !defined(__MINGW32__)
306 // Opens a file and constructs a file object representing this file by
307 // wcstring_view filename. Windows only.
308 static file
open_windows_file(wcstring_view path
, int oflag
);
312 struct FMT_API pipe
{
316 // Creates a pipe setting up read_end and write_end file objects for reading
317 // and writing respectively.
321 // Returns the memory page size.
322 auto getpagesize() -> long;
327 buffer_size() = default;
329 auto operator=(size_t val
) const -> buffer_size
{
330 auto bs
= buffer_size();
336 struct ostream_params
{
337 int oflag
= file::WRONLY
| file::CREATE
| file::TRUNC
;
338 size_t buffer_size
= BUFSIZ
> 32768 ? BUFSIZ
: 32768;
342 template <typename
... T
>
343 ostream_params(T
... params
, int new_oflag
) : ostream_params(params
...) {
347 template <typename
... T
>
348 ostream_params(T
... params
, detail::buffer_size bs
)
349 : ostream_params(params
...) {
350 this->buffer_size
= bs
.value
;
353 // Intel has a bug that results in failure to deduce a constructor
354 // for empty parameter packs.
355 # if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000
356 ostream_params(int new_oflag
) : oflag(new_oflag
) {}
357 ostream_params(detail::buffer_size bs
) : buffer_size(bs
.value
) {}
361 class file_buffer final
: public buffer
<char> {
365 FMT_API
static void grow(buffer
<char>& buf
, size_t);
368 FMT_API
file_buffer(cstring_view path
, const ostream_params
& params
);
369 FMT_API
file_buffer(file_buffer
&& other
) noexcept
;
370 FMT_API
~file_buffer();
373 if (size() == 0) return;
374 file_
.write(data(), size() * sizeof(data()[0]));
384 } // namespace detail
386 constexpr auto buffer_size
= detail::buffer_size();
388 /// A fast output stream for writing from a single thread. Writing from
389 /// multiple threads without external synchronization may result in a data race.
390 class FMT_API ostream
{
392 FMT_MSC_WARNING(suppress
: 4251)
393 detail::file_buffer buffer_
;
395 ostream(cstring_view path
, const detail::ostream_params
& params
)
396 : buffer_(path
, params
) {}
399 ostream(ostream
&& other
) : buffer_(std::move(other
.buffer_
)) {}
403 void flush() { buffer_
.flush(); }
405 template <typename
... T
>
406 friend auto output_file(cstring_view path
, T
... params
) -> ostream
;
408 void close() { buffer_
.close(); }
410 /// Formats `args` according to specifications in `fmt` and writes the
411 /// output to the file.
412 template <typename
... T
> void print(format_string
<T
...> fmt
, T
&&... args
) {
413 vformat_to(appender(buffer_
), fmt
, fmt::make_format_args(args
...));
418 * Opens a file for writing. Supported parameters passed in `params`:
420 * - `<integer>`: Flags passed to [open](
421 * https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html)
422 * (`file::WRONLY | file::CREATE | file::TRUNC` by default)
423 * - `buffer_size=<integer>`: Output buffer size
427 * auto out = fmt::output_file("guide.txt");
428 * out.print("Don't {}", "Panic");
430 template <typename
... T
>
431 inline auto output_file(cstring_view path
, T
... params
) -> ostream
{
432 return {path
, detail::ostream_params(params
...)};
434 #endif // FMT_USE_FCNTL
This page took 0.041129 seconds and 5 git commands to generate.