| Yuxiao Zhang | 1e76060 | 2024-03-07 12:35:24 -0800 | [diff] [blame] | 1 | #include "file-io.hpp" | 
|  | 2 |  | 
|  | 3 | #include <fcntl.h> | 
|  | 4 | #include <sys/file.h> | 
|  | 5 | #include <unistd.h> | 
|  | 6 |  | 
|  | 7 | #include <stdplus/fd/atomic.hpp> | 
|  | 8 | #include <stdplus/fd/create.hpp> | 
|  | 9 | #include <stdplus/fd/fmt.hpp> | 
|  | 10 | #include <stdplus/fd/managed.hpp> | 
|  | 11 | #include <stdplus/fd/ops.hpp> | 
|  | 12 | #include <stdplus/print.hpp> | 
|  | 13 |  | 
|  | 14 | #include <cerrno> | 
|  | 15 | #include <fstream> | 
|  | 16 | #include <iostream> | 
|  | 17 | #include <string> | 
|  | 18 |  | 
|  | 19 | using ::stdplus::fd::ManagedFd; | 
|  | 20 | using std::literals::string_view_literals::operator""sv; | 
|  | 21 |  | 
|  | 22 | // Function to read contents from a file (with locking) | 
|  | 23 | std::string fileRead(const fs::path& filename) | 
|  | 24 | { | 
|  | 25 | // Open the file in read mode | 
|  | 26 | ManagedFd fd = stdplus::fd::open(std::string(filename).c_str(), | 
|  | 27 | stdplus::fd::OpenAccess::ReadOnly); | 
|  | 28 | return stdplus::fd::readAll<std::string>(fd); | 
|  | 29 | } | 
|  | 30 |  | 
|  | 31 | // Function to write contents to a file atomically | 
|  | 32 | void fileWrite(const fs::path& filename, const std::string& data) | 
|  | 33 | { | 
|  | 34 | stdplus::fd::AtomicWriter writer(filename, 0644); | 
|  | 35 | stdplus::fd::FormatBuffer out(writer); | 
|  | 36 | out.appends(data); | 
|  | 37 | out.flush(); | 
|  | 38 | writer.commit(); | 
|  | 39 | } |