/src/glaze/include/glaze/file/file_ops.hpp
Line | Count | Source |
1 | | // Glaze Library |
2 | | // For the license information refer to glaze.hpp |
3 | | |
4 | | #pragma once |
5 | | |
6 | | #include <cstdio> |
7 | | #include <filesystem> |
8 | | #include <string> |
9 | | |
10 | | #include "glaze/core/context.hpp" |
11 | | |
12 | | #if defined(_MSC_VER) && !defined(__clang__) |
13 | | // Turn off MSVC warning for unsafe fopen |
14 | | #pragma warning(push) |
15 | | #pragma warning(disable : 4996) |
16 | | #endif |
17 | | |
18 | | namespace glz |
19 | | { |
20 | | template <class T> |
21 | | [[nodiscard]] error_code file_to_buffer(T& buffer, auto* file, const std::string_view path) |
22 | | { |
23 | | if (!file) { |
24 | | return error_code::file_open_failure; |
25 | | } |
26 | | |
27 | | std::error_code ec{}; |
28 | | const auto n = std::filesystem::file_size(path, ec); |
29 | | if (ec) { |
30 | | std::fclose(file); |
31 | | return error_code::file_open_failure; |
32 | | } |
33 | | buffer.resize(n); |
34 | | |
35 | | // file_size() and the read below observe the file at two different moments, |
36 | | // so the file may have changed size in between (e.g. a concurrent atomic |
37 | | // replace). Trust the bytes actually read from the open handle, not the stat: |
38 | | // a short read that is not a stream error simply means the file was smaller |
39 | | // than reported, so keep exactly what was read instead of failing. This keeps |
40 | | // the common case a single fread with no added cost. |
41 | | const auto read = std::fread(static_cast<void*>(buffer.data()), 1, n, file); |
42 | | if (read != n) { |
43 | | if (std::ferror(file)) { |
44 | | std::fclose(file); |
45 | | return error_code::file_open_failure; |
46 | | } |
47 | | buffer.resize(read); |
48 | | } |
49 | | |
50 | | if (std::fclose(file)) { |
51 | | return error_code::file_close_failure; |
52 | | } |
53 | | |
54 | | return {}; |
55 | | } |
56 | | |
57 | | template <class T> |
58 | | [[nodiscard]] error_code file_to_buffer(T& buffer, const std::string_view file_name) |
59 | | { |
60 | | auto* file = std::fopen(file_name.data(), "rb"); |
61 | | return file_to_buffer(buffer, file, file_name); |
62 | | } |
63 | | |
64 | | template <class T> |
65 | | std::string file_to_buffer(T&& file_name) |
66 | | { |
67 | | std::string buffer{}; |
68 | | file_to_buffer(buffer, std::forward<T>(file_name)); |
69 | | return buffer; |
70 | | } |
71 | | |
72 | | inline std::filesystem::path relativize_if_not_absolute(const std::filesystem::path& working_directory, |
73 | | const std::filesystem::path& filepath) |
74 | 0 | { |
75 | 0 | if (filepath.is_absolute()) { |
76 | 0 | return filepath; |
77 | 0 | } |
78 | 0 |
|
79 | 0 | return working_directory / filepath; |
80 | 0 | } |
81 | | } |
82 | | |
83 | | #if defined(_MSC_VER) && !defined(__clang__) |
84 | | // restore disabled warning |
85 | | #pragma warning(pop) |
86 | | #endif |