7#include <packager/file/local_file.h>
13#include <system_error>
15#include <packager/file.h>
25#include <absl/log/check.h>
26#include <absl/log/log.h>
32const char kAdditionalFileMode[] =
"b";
35 : File(file_name), file_mode_(mode), internal_file_(NULL) {
36 if (file_mode_.find(kAdditionalFileMode) == std::string::npos)
37 file_mode_ += kAdditionalFileMode;
40bool LocalFile::Close() {
43 result = fclose(internal_file_) == 0;
44 internal_file_ = NULL;
50int64_t LocalFile::Read(
void* buffer, uint64_t length) {
51 DCHECK(buffer != NULL);
52 DCHECK(internal_file_ != NULL);
53 size_t bytes_read = fread(buffer,
sizeof(
char), length, internal_file_);
54 VLOG(2) <<
"Read " << length <<
" return " << bytes_read <<
" error "
55 << ferror(internal_file_);
56 if (bytes_read == 0 && ferror(internal_file_) != 0) {
62int64_t LocalFile::Write(
const void* buffer, uint64_t length) {
63 DCHECK(buffer != NULL);
64 DCHECK(internal_file_ != NULL);
65 size_t bytes_written = fwrite(buffer,
sizeof(
char), length, internal_file_);
66 VLOG(2) <<
"Write " << length <<
" return " << bytes_written <<
" error "
67 << ferror(internal_file_);
68 if (bytes_written == 0 && ferror(internal_file_) != 0) {
74void LocalFile::CloseForWriting() {}
76int64_t LocalFile::Size() {
77 DCHECK(internal_file_ != NULL);
81 LOG(ERROR) <<
"Cannot flush file.";
86 auto file_path = std::filesystem::u8path(file_name());
87 int64_t file_size = std::filesystem::file_size(file_path, ec);
89 LOG(ERROR) <<
"Cannot get file size, error: " << ec;
95bool LocalFile::Flush() {
96 DCHECK(internal_file_ != NULL);
97 return ((fflush(internal_file_) == 0) && !ferror(internal_file_));
100bool LocalFile::Seek(uint64_t position) {
102 return _fseeki64(internal_file_,
static_cast<__int64
>(position), SEEK_SET) ==
105 return fseeko(internal_file_, position, SEEK_SET) >= 0;
109bool LocalFile::Tell(uint64_t* position) {
111 __int64 offset = _ftelli64(internal_file_);
113 off_t offset = ftello(internal_file_);
117 *position =
static_cast<uint64_t
>(offset);
121LocalFile::~LocalFile() {}
123bool LocalFile::Open() {
124 auto file_path = std::filesystem::u8path(file_name());
127 if (file_mode_.find(
"w") != std::string::npos) {
131 auto parent_path = file_path.parent_path();
133 if (parent_path !=
"" && !std::filesystem::is_directory(parent_path, ec)) {
134 if (!std::filesystem::create_directories(parent_path, ec)) {
143 internal_file_ = fopen(file_path.u8string().c_str(), file_mode_.c_str());
144 return (internal_file_ != NULL);
148 auto file_path = std::filesystem::u8path(file_name);
151 return std::filesystem::remove(file_path, ec);
LocalFile(const char *file_name, const char *mode)
static bool Delete(const char *file_name)
All the methods that are virtual are virtual for mocking.