flatten 20260225
This commit is contained in:
66
tjp/core/file/write.cpp
Normal file
66
tjp/core/file/write.cpp
Normal file
@@ -0,0 +1,66 @@
|
||||
// TJP COPYRIGHT HEADER
|
||||
|
||||
|
||||
#ifdef TJP_CORE_HEADER_ONLY
|
||||
#pragma once
|
||||
#endif
|
||||
|
||||
#include <tjp/core/header_only/compile.h>
|
||||
|
||||
#include "write.hpp"
|
||||
#include <tjp/core/exception/Exception.hpp>
|
||||
#include "../random/file_name.hpp"
|
||||
#include "times.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
|
||||
namespace tjp::core::file {
|
||||
|
||||
TJP_CORE_HEADER_ONLY_INLINE
|
||||
bool write(const String &path_, const ContentsView &contents, const WriteOptions &options)
|
||||
{
|
||||
auto path = String(path_);
|
||||
auto random_ = random::file_name();
|
||||
|
||||
auto extension = "." + random_;
|
||||
auto temporary = path + extension;
|
||||
|
||||
std::ofstream file(temporary, std::ios::binary);
|
||||
if (!file)
|
||||
return false;
|
||||
|
||||
file.write(contents.data(), contents.size());
|
||||
file.close();
|
||||
|
||||
remove(path.c_str());
|
||||
if (rename(temporary.c_str(), path.c_str()))
|
||||
return false;
|
||||
|
||||
if (options.lastModifiedTime)
|
||||
setFileLastModifiedTime(path, options.lastModifiedTime);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
TJP_CORE_HEADER_ONLY_INLINE
|
||||
void require_write(const String &path, const ContentsView &contents, const WriteOptions &options)
|
||||
{
|
||||
if (!write(path, contents, options))
|
||||
throw Exception { "failed to write file " + String(path) };
|
||||
}
|
||||
|
||||
TJP_CORE_HEADER_ONLY_INLINE
|
||||
bool write(const StringView &path, const ContentsView &contents, const WriteOptions &options)
|
||||
{
|
||||
return write(String(path), contents, options);
|
||||
}
|
||||
|
||||
TJP_CORE_HEADER_ONLY_INLINE
|
||||
void require_write(const StringView &path, const ContentsView &contents, const WriteOptions &options)
|
||||
{
|
||||
return require_write(String(path), contents, options);
|
||||
}
|
||||
|
||||
|
||||
} // namespace
|
||||
Reference in New Issue
Block a user