userver: userver/fs/blocking/c_file.hpp Source File
Loading...
Searching...
No Matches
c_file.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/fs/blocking/c_file.hpp
4/// @brief @copybrief fs::blocking::CFile
5
6#include <cstdint>
7#include <cstdio>
8#include <span>
9#include <string_view>
10
11#include <userver/utils/boost_filesystem_file_status.hpp>
12#include <userver/utils/zstring_view.hpp>
13
14#include <userver/fs/blocking/open_mode.hpp>
15#include <userver/utils/fast_pimpl.hpp>
16
17USERVER_NAMESPACE_BEGIN
18
19namespace fs::blocking {
20
21/// @ingroup userver_universal userver_containers
22///
23/// @brief A `std::FILE*` wrapper
24/// @details The file is closed in the destructor
25/// @note The operations on the file are blocking and not thread-safe
26class CFile final {
27public:
28 /// Creates an empty file handle
30
31 CFile(CFile&&) noexcept;
32 CFile& operator=(CFile&&) noexcept;
33 ~CFile();
34
35 /// @brief Opens the file
36 /// @throws std::runtime_error
38 utils::zstring_view path,
39 OpenMode flags,
40 boost::filesystem::perms perms = boost::filesystem::perms::owner_read | boost::filesystem::perms::owner_write
41 );
42
43 /// @brief Adopt the `std::FILE*` directly
44 explicit CFile(std::FILE* file) noexcept;
45
46 /// Checks if the file is open
47 bool IsOpen() const noexcept;
48
49 /// Returns the underlying file handle
50 std::FILE* GetNative() &;
51
52 /// Passes the ownership of the file to the caller
53 std::FILE* Release() &&;
54
55 /// @brief Closes the file manually
56 /// @throws std::runtime_error
57 void Close() &&;
58
59 /// @brief Reads data from the file
60 /// @returns The amount of bytes actually acquired, which can be equal
61 /// to `max_size`, or less on end-of-file
62 /// @throws std::runtime_error
63 std::size_t Read(std::span<char> buffer);
64
65 /// @brief Writes data to the file
66 /// @warning Unless `Flush` is called, there is no guarantee the file on disk
67 /// is actually updated
68 /// @throws std::runtime_error
69 void Write(std::string_view data);
70
71 /// @brief Synchronizes the written data with the file on disk
72 /// @throws std::runtime_error
73 void Flush();
74
75 /// @brief Synchronizes the written data with the file on disk
76 /// without fsync
77 /// @throws std::runtime_error
78 void FlushLight();
79
80 /// @brief Fetches the current position in the file
81 /// @throws std::runtime_error
82 std::uint64_t GetPosition() const;
83
84 /// @brief Fetches the file size
85 /// @throws std::runtime_error
86 std::uint64_t GetSize() const;
87
88private:
89 struct Impl;
90 utils::FastPimpl<Impl, sizeof(char*), alignof(char*)> impl_;
91};
92
93} // namespace fs::blocking
94
95USERVER_NAMESPACE_END