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.
14 #include <system_error> // std::system_error
16 #if defined __APPLE__ || defined(__FreeBSD__)
17 # include <xlocale.h> // for LC_NUMERIC_MASK on OS X
23 // UWP doesn't provide _pipe.
24 # if FMT_HAS_INCLUDE("winapifamily.h")
25 # include <winapifamily.h>
27 # if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
28 defined(__linux__)) && \
29 (!defined(WINAPI_FAMILY) || \
30 (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
31 # include <fcntl.h> // for O_RDONLY
32 # define FMT_USE_FCNTL 1
34 # define FMT_USE_FCNTL 0
39 # if defined(_WIN32) && !defined(__MINGW32__)
40 // Fix warnings about deprecated symbols.
41 # define FMT_POSIX(call) _##call
43 # define FMT_POSIX(call) call
47 // Calls to system functions are wrapped in FMT_SYSTEM for testability.
49 # define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
51 # define FMT_SYSTEM(call) ::call
53 // Fix warnings about deprecated symbols.
54 # define FMT_POSIX_CALL(call) ::_##call
56 # define FMT_POSIX_CALL(call) ::call
60 // Retries the expression while it evaluates to error_result and errno
63 # define FMT_RETRY_VAL(result, expression, error_result) \
65 (result) = (expression); \
66 } while ((result) == (error_result) && errno == EINTR)
68 # define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
71 #define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
78 A reference to a null-terminated string. It can be constructed from a C
79 string or ``std::string``.
81 You can use one of the following type aliases for common character types:
83 +---------------+-----------------------------+
85 +===============+=============================+
86 | cstring_view | basic_cstring_view<char> |
87 +---------------+-----------------------------+
88 | wcstring_view | basic_cstring_view<wchar_t> |
89 +---------------+-----------------------------+
91 This class is most useful as a parameter type to allow passing
92 different types of strings to a function, for example::
94 template <typename... Args>
95 std::string format(cstring_view format_str, const Args & ... args);
98 format(std::string("{}"), 42);
101 template <typename Char
> class basic_cstring_view
{
106 /** Constructs a string reference object from a C string. */
107 basic_cstring_view(const Char
* s
) : data_(s
) {}
111 Constructs a string reference from an ``std::string`` object.
114 basic_cstring_view(const std::basic_string
<Char
>& s
) : data_(s
.c_str()) {}
116 /** Returns the pointer to a C string. */
117 const Char
* c_str() const { return data_
; }
120 using cstring_view
= basic_cstring_view
<char>;
121 using wcstring_view
= basic_cstring_view
<wchar_t>;
124 FMT_API
const std::error_category
& system_category() noexcept
;
127 FMT_API
void format_windows_error(buffer
<char>& out
, int error_code
,
128 const char* message
) noexcept
;
131 FMT_API
std::system_error
vwindows_error(int error_code
, string_view format_str
,
136 Constructs a :class:`std::system_error` object with the description
140 *<message>*: *<system-message>*
142 where *<message>* is the formatted message and *<system-message>* is the
143 system message corresponding to the error code.
144 *error_code* is a Windows error code as given by ``GetLastError``.
145 If *error_code* is not a valid error code such as -1, the system message
146 will look like "error -1".
150 // This throws a system_error with the description
151 // cannot open file 'madeup': The system cannot find the file specified.
152 // or similar (system message may vary).
153 const char *filename = "madeup";
154 LPOFSTRUCT of = LPOFSTRUCT();
155 HFILE file = OpenFile(filename, &of, OF_READ);
156 if (file == HFILE_ERROR) {
157 throw fmt::windows_error(GetLastError(),
158 "cannot open file '{}'", filename);
162 template <typename
... Args
>
163 std::system_error
windows_error(int error_code
, string_view message
,
164 const Args
&... args
) {
165 return vwindows_error(error_code
, message
, fmt::make_format_args(args
...));
168 // Reports a Windows error without throwing an exception.
169 // Can be used to report errors from destructors.
170 FMT_API
void report_windows_error(int error_code
, const char* message
) noexcept
;
172 inline const std::error_category
& system_category() noexcept
{
173 return std::system_category();
177 // std::system is not available on some platforms such as iOS (#2248).
179 template <typename S
, typename
... Args
, typename Char
= char_t
<S
>>
180 void say(const S
& format_str
, Args
&&... args
) {
181 std::system(format("say \"{}\"", format(format_str
, args
...)).c_str());
186 class buffered_file
{
192 explicit buffered_file(FILE* f
) : file_(f
) {}
195 buffered_file(const buffered_file
&) = delete;
196 void operator=(const buffered_file
&) = delete;
198 // Constructs a buffered_file object which doesn't represent any file.
199 buffered_file() noexcept
: file_(nullptr) {}
201 // Destroys the object closing the file it represents if any.
202 FMT_API
~buffered_file() noexcept
;
205 buffered_file(buffered_file
&& other
) noexcept
: file_(other
.file_
) {
206 other
.file_
= nullptr;
209 buffered_file
& operator=(buffered_file
&& other
) {
212 other
.file_
= nullptr;
217 FMT_API
buffered_file(cstring_view filename
, cstring_view mode
);
220 FMT_API
void close();
222 // Returns the pointer to a FILE object representing this file.
223 FILE* get() const noexcept
{ return file_
; }
225 FMT_API
int descriptor() const;
227 void vprint(string_view format_str
, format_args args
) {
228 fmt::vprint(file_
, format_str
, args
);
231 template <typename
... Args
>
232 inline void print(string_view format_str
, const Args
&... args
) {
233 vprint(format_str
, fmt::make_format_args(args
...));
238 // A file. Closed file is represented by a file object with descriptor -1.
239 // Methods that are not declared with noexcept may throw
240 // fmt::system_error in case of failure. Note that some errors such as
241 // closing the file multiple times will cause a crash on Windows rather
242 // than an exception. You can get standard behavior by overriding the
243 // invalid parameter handler with _set_invalid_parameter_handler.
246 int fd_
; // File descriptor.
248 // Constructs a file object with a given descriptor.
249 explicit file(int fd
) : fd_(fd
) {}
252 // Possible values for the oflag argument to the constructor.
254 RDONLY
= FMT_POSIX(O_RDONLY
), // Open for reading only.
255 WRONLY
= FMT_POSIX(O_WRONLY
), // Open for writing only.
256 RDWR
= FMT_POSIX(O_RDWR
), // Open for reading and writing.
257 CREATE
= FMT_POSIX(O_CREAT
), // Create if the file doesn't exist.
258 APPEND
= FMT_POSIX(O_APPEND
), // Open in append mode.
259 TRUNC
= FMT_POSIX(O_TRUNC
) // Truncate the content of the file.
262 // Constructs a file object which doesn't represent any file.
263 file() noexcept
: fd_(-1) {}
265 // Opens a file and constructs a file object representing this file.
266 file(cstring_view path
, int oflag
);
269 file(const file
&) = delete;
270 void operator=(const file
&) = delete;
272 file(file
&& other
) noexcept
: fd_(other
.fd_
) { other
.fd_
= -1; }
274 // Move assignment is not noexcept because close may throw.
275 file
& operator=(file
&& other
) {
282 // Destroys the object closing the file it represents if any.
285 // Returns the file descriptor.
286 int descriptor() const noexcept
{ return fd_
; }
291 // Returns the file size. The size has signed type for consistency with
293 long long size() const;
295 // Attempts to read count bytes from the file into the specified buffer.
296 size_t read(void* buffer
, size_t count
);
298 // Attempts to write count bytes from the specified buffer to the file.
299 size_t write(const void* buffer
, size_t count
);
301 // Duplicates a file descriptor with the dup function and returns
302 // the duplicate as a file object.
303 static file
dup(int fd
);
305 // Makes fd be the copy of this file descriptor, closing fd first if
309 // Makes fd be the copy of this file descriptor, closing fd first if
311 void dup2(int fd
, std::error_code
& ec
) noexcept
;
313 // Creates a pipe setting up read_end and write_end file objects for reading
314 // and writing respectively.
315 static void pipe(file
& read_end
, file
& write_end
);
317 // Creates a buffered_file object associated with this file and detaches
318 // this file object from the file.
319 buffered_file
fdopen(const char* mode
);
321 # if defined(_WIN32) && !defined(__MINGW32__)
322 // Opens a file and constructs a file object representing this file by
323 // wcstring_view filename. Windows only.
324 static file
open_windows_file(wcstring_view path
, int oflag
);
328 // Returns the memory page size.
334 buffer_size() = default;
336 buffer_size
operator=(size_t val
) const {
337 auto bs
= buffer_size();
343 struct ostream_params
{
344 int oflag
= file::WRONLY
| file::CREATE
| file::TRUNC
;
345 size_t buffer_size
= BUFSIZ
> 32768 ? BUFSIZ
: 32768;
349 template <typename
... T
>
350 ostream_params(T
... params
, int new_oflag
) : ostream_params(params
...) {
354 template <typename
... T
>
355 ostream_params(T
... params
, detail::buffer_size bs
)
356 : ostream_params(params
...) {
357 this->buffer_size
= bs
.value
;
360 // Intel has a bug that results in failure to deduce a constructor
361 // for empty parameter packs.
362 # if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000
363 ostream_params(int new_oflag
) : oflag(new_oflag
) {}
364 ostream_params(detail::buffer_size bs
) : buffer_size(bs
.value
) {}
368 class file_buffer final
: public buffer
<char> {
371 FMT_API
void grow(size_t) override
;
374 FMT_API
file_buffer(cstring_view path
, const ostream_params
& params
);
375 FMT_API
file_buffer(file_buffer
&& other
);
376 FMT_API
~file_buffer();
379 if (size() == 0) return;
380 file_
.write(data(), size() * sizeof(data()[0]));
390 } // namespace detail
392 // Added {} below to work around default constructor error known to
393 // occur in Xcode versions 7.2.1 and 8.2.1.
394 constexpr detail::buffer_size buffer_size
{};
396 /** A fast output stream which is not thread-safe. */
397 class FMT_API ostream
{
399 FMT_MSC_WARNING(suppress
: 4251)
400 detail::file_buffer buffer_
;
402 ostream(cstring_view path
, const detail::ostream_params
& params
)
403 : buffer_(path
, params
) {}
406 ostream(ostream
&& other
) : buffer_(std::move(other
.buffer_
)) {}
410 void flush() { buffer_
.flush(); }
412 template <typename
... T
>
413 friend ostream
output_file(cstring_view path
, T
... params
);
415 void close() { buffer_
.close(); }
418 Formats ``args`` according to specifications in ``fmt`` and writes the
421 template <typename
... T
> void print(format_string
<T
...> fmt
, T
&&... args
) {
422 vformat_to(detail::buffer_appender
<char>(buffer_
), fmt
,
423 fmt::make_format_args(args
...));
429 Opens a file for writing. Supported parameters passed in *params*:
431 * ``<integer>``: Flags passed to `open
432 <https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html>`_
433 (``file::WRONLY | file::CREATE | file::TRUNC`` by default)
434 * ``buffer_size=<integer>``: Output buffer size
438 auto out = fmt::output_file("guide.txt");
439 out.print("Don't {}", "Panic");
442 template <typename
... T
>
443 inline ostream
output_file(cstring_view path
, T
... params
) {
444 return {path
, detail::ostream_params(params
...)};
446 #endif // FMT_USE_FCNTL
This page took 0.037747 seconds and 4 git commands to generate.