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