userver: userver/fs/blocking/file_descriptor.hpp Source File
Loading...
Searching...
No Matches
file_descriptor.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/fs/blocking/file_descriptor.hpp
4/// @brief @copybrief fs::blocking::FileDescriptor
5
6#include <string>
7#include <string_view>
8
9#include <userver/utils/boost_filesystem_file_status.hpp>
10
11#include <userver/fs/blocking/open_mode.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace fs::blocking {
16
17/// @ingroup userver_universal userver_containers
18///
19/// @brief A file descriptor wrapper
20/// @details The file is closed in the destructor
21/// @note The operations on the file are blocking and not thread-safe
22class FileDescriptor final {
23public:
24 /// @brief Open a file using ::open
25 /// @throws std::runtime_error
26 static FileDescriptor Open(
27 const std::string& path,
28 OpenMode flags,
29 boost::filesystem::perms perms = boost::filesystem::perms::owner_read | boost::filesystem::perms::owner_write
30 );
31
32 /// @brief Open a directory node
33 /// @note The only valid operation for such a `FileDescriptor` is `FSync`.
34 /// @throws std::runtime_error
35 static FileDescriptor OpenDirectory(const std::string& path);
36
37 /// @brief Use the file descriptor directly
38 static FileDescriptor AdoptFd(int fd) noexcept;
39
40 FileDescriptor() = delete;
41 FileDescriptor(FileDescriptor&& other) noexcept;
42 FileDescriptor& operator=(FileDescriptor&& other) noexcept;
43 ~FileDescriptor();
44
45 /// @brief Checks if the file is open
46 /// @note Operations can only be performed on an open `FileDescriptor`.
47 bool IsOpen() const;
48
49 /// @brief Closes the file manually
50 /// @throws std::runtime_error
51 void Close() &&;
52
53 /// Returns the native file handle
54 int GetNative() const;
55
56 /// Passes the ownership of the file descriptor to the caller
57 int Release() &&;
58
59 /// @brief Writes data to the file
60 /// @warning Unless `FSync` is called, there is no guarantee the data
61 /// is stored on disk safely.
62 /// @throws std::runtime_error
63 void Write(std::string_view contents);
64
65 /// @brief Reads data from the file at current offset
66 /// @returns The amount of bytes actually acquired, which can be equal
67 /// to `max_size`, or less on end-of-file
68 /// @throws std::runtime_error
69 std::size_t Read(char* buffer, std::size_t max_size);
70
71 /// @brief Sets the file read/write offset from the beginning of the file
72 /// @throws std::runtime_error
73 void Seek(std::size_t offset_in_bytes);
74
75 /// @brief Makes sure the written data is actually stored on disk
76 /// @throws std::runtime_error
77 void FSync();
78
79 /// @brief Fetches the file size
80 /// @throws std::runtime_error
81 std::size_t GetSize() const;
82
83private:
84 explicit FileDescriptor(int fd);
85
86 friend class TempFile;
87
88 int fd_;
89};
90
91} // namespace fs::blocking
92
93USERVER_NAMESPACE_END