blob: 321cc6d538afd929f373f643ca27ab752f5bf31b [file] [log] [blame]
Yuxiao Zhang1e760602024-03-07 12:35:24 -08001#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
19using ::stdplus::fd::ManagedFd;
20using std::literals::string_view_literals::operator""sv;
21
22// Function to read contents from a file (with locking)
23std::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
32void 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}