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