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