7 #include <packager/file/local_file.h>
18 #include <absl/log/check.h>
19 #include <absl/log/log.h>
21 #include <packager/macros/logging.h>
26 const char kAdditionalFileMode[] =
"b";
29 : File(file_name), file_mode_(mode), internal_file_(NULL) {
30 if (file_mode_.find(kAdditionalFileMode) == std::string::npos)
31 file_mode_ += kAdditionalFileMode;
34 bool LocalFile::Close() {
37 result = fclose(internal_file_) == 0;
38 internal_file_ = NULL;
44 int64_t LocalFile::Read(
void* buffer, uint64_t length) {
45 DCHECK(buffer != NULL);
46 DCHECK(internal_file_ != NULL);
47 size_t bytes_read = fread(buffer,
sizeof(
char), length, internal_file_);
48 VLOG(2) <<
"Read " << length <<
" return " << bytes_read <<
" error "
49 << ferror(internal_file_);
50 if (bytes_read == 0 && ferror(internal_file_) != 0) {
56 int64_t LocalFile::Write(
const void* buffer, uint64_t length) {
57 DCHECK(buffer != NULL);
58 DCHECK(internal_file_ != NULL);
59 size_t bytes_written = fwrite(buffer,
sizeof(
char), length, internal_file_);
60 VLOG(2) <<
"Write " << length <<
" return " << bytes_written <<
" error "
61 << ferror(internal_file_);
62 if (bytes_written == 0 && ferror(internal_file_) != 0) {
68 void LocalFile::CloseForWriting() {}
70 int64_t LocalFile::Size() {
71 DCHECK(internal_file_ != NULL);
75 LOG(ERROR) <<
"Cannot flush file.";
80 auto file_path = std::filesystem::u8path(file_name());
81 int64_t file_size = std::filesystem::file_size(file_path, ec);
83 LOG(ERROR) <<
"Cannot get file size, error: " << ec;
89 bool LocalFile::Flush() {
90 DCHECK(internal_file_ != NULL);
91 return ((fflush(internal_file_) == 0) && !ferror(internal_file_));
94 bool LocalFile::Seek(uint64_t position) {
96 return _fseeki64(internal_file_,
static_cast<__int64
>(position), SEEK_SET) ==
99 return fseeko(internal_file_, position, SEEK_SET) >= 0;
103 bool LocalFile::Tell(uint64_t* position) {
105 __int64 offset = _ftelli64(internal_file_);
107 off_t offset = ftello(internal_file_);
111 *position =
static_cast<uint64_t
>(offset);
115 LocalFile::~LocalFile() {}
117 bool LocalFile::Open() {
118 auto file_path = std::filesystem::u8path(file_name());
121 if (file_mode_.find(
"w") != std::string::npos) {
125 auto parent_path = file_path.parent_path();
127 if (parent_path !=
"" && !std::filesystem::is_directory(parent_path, ec)) {
128 if (!std::filesystem::create_directories(parent_path, ec)) {
134 internal_file_ = fopen(file_path.u8string().c_str(), file_mode_.c_str());
135 return (internal_file_ != NULL);
139 auto file_path = std::filesystem::u8path(file_name);
142 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.