Abstract away file writing logic

This commit is contained in:
Adubbz 2019-08-07 20:43:48 +10:00
parent fac8acebba
commit 7dce15bcda
3 changed files with 26 additions and 40 deletions

View file

@ -157,27 +157,7 @@ namespace sts::ncm {
this->placeholder_accessor.StoreToCache(f, placeholder_id);
};
if (fseek(f, 0, SEEK_END) != 0) {
return fsdevGetLastResult();
}
u64 size = ftell(f);
/* We can't disable append with stdio, so check this manually. */
if (offset + data.num_elements > size) {
return ResultFileExtensionWithoutOpenModeAllowAppend;
}
if (fseek(f, offset, SEEK_SET) != 0) {
return fsdevGetLastResult();
}
if (fwrite(data.buffer, sizeof(u8), data.num_elements, f) != data.num_elements) {
return fsdevGetLastResult();
}
if (!this->placeholder_accessor.delay_flush) {
fflush(f);
}
R_TRY(WriteFile(f, offset, data.buffer, data.num_elements, !this->placeholder_accessor.delay_flush));
return ResultSuccess;
R_DEBUG_END
@ -601,25 +581,7 @@ namespace sts::ncm {
fclose(f);
};
if (fseek(f, 0, SEEK_END) != 0) {
return fsdevGetLastResult();
}
u64 size = ftell(f);
/* We can't disable append with stdio, so check this manually. */
if (offset + data.num_elements > size) {
return ResultFileExtensionWithoutOpenModeAllowAppend;
}
if (fseek(f, offset, SEEK_SET) != 0) {
return fsdevGetLastResult();
}
if (fwrite(data.buffer, sizeof(u8), data.num_elements, f) != data.num_elements) {
return fsdevGetLastResult();
}
fflush(f);
R_TRY(WriteFile(f, offset, data.buffer, data.num_elements, FS_WRITEOPTION_FLUSH));
return ResultSuccess;
R_DEBUG_END

View file

@ -21,6 +21,8 @@
#include "ncm_fs.hpp"
#include "ncm_path_utils.hpp"
#include "debug.hpp"
namespace sts::ncm {
Result OpenFile(FILE** out, const char* path, u32 mode) {
@ -58,6 +60,26 @@ namespace sts::ncm {
return ResultSuccess;
}
Result WriteFile(FILE* f, size_t offset, const void* buffer, size_t size, u32 option) {
R_DEBUG_START
D_LOG("Writing 0x%llx to offset 0x%llx\n", size, offset);
if (fseek(f, offset, SEEK_SET) != 0) {
return fsdevGetLastResult();
}
if (fwrite(buffer, size, 1, f) != 1) {
return fsdevGetLastResult();
}
if (option & FS_WRITEOPTION_FLUSH) {
fflush(f);
}
return ResultSuccess;
R_DEBUG_END
}
Result HasFile(bool* out, const char* path) {
struct stat st;

View file

@ -24,6 +24,8 @@
namespace sts::ncm {
Result OpenFile(FILE** out, const char* path, u32 mode);
Result WriteFile(FILE* f, size_t offset, const void* buffer, size_t size, u32 option);
Result HasFile(bool* out, const char* path);
Result HasDirectory(bool* out, const char* path);