New File tools
This commit is contained in:
108
src/dawntools/util/File.hpp
Normal file
108
src/dawntools/util/File.hpp
Normal file
@ -0,0 +1,108 @@
|
||||
// Copyright (c) 2023 Dominic Masters
|
||||
//
|
||||
// This software is released under the MIT License.
|
||||
// https://opensource.org/licenses/MIT
|
||||
|
||||
#pragma once
|
||||
#include "assert/assert.hpp"
|
||||
#include "util/file.hpp"
|
||||
#include "util/mathutils.hpp"
|
||||
|
||||
#define FILE_BUFFER_SIZE 512
|
||||
|
||||
namespace Dawn {
|
||||
enum FileMode {
|
||||
FILE_MODE_READ,
|
||||
FILE_MODE_WRITE
|
||||
};
|
||||
|
||||
class File {
|
||||
private:
|
||||
FILE *file = nullptr;
|
||||
enum FileMode mode;
|
||||
size_t length;
|
||||
|
||||
public:
|
||||
std::string filename;
|
||||
|
||||
File(std::string filename) {
|
||||
this->filename = fileNormalizeSlashesNew(filename);
|
||||
}
|
||||
|
||||
bool_t open(enum FileMode mode) {
|
||||
assertNull(this->file);
|
||||
|
||||
this->mode = mode;
|
||||
this->file = fopen(
|
||||
this->filename.c_str(),
|
||||
mode == FILE_MODE_READ ? "rb" : "wb"
|
||||
);
|
||||
|
||||
if(this->file == NULL) return false;
|
||||
|
||||
fseek(this->file, 0, SEEK_END);
|
||||
this->length = ftell(this->file);
|
||||
fseek(this->file, 0, SEEK_SET);
|
||||
|
||||
if(this->length <= 0) {
|
||||
this->close();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool_t isOpen() {
|
||||
return this->file != nullptr;
|
||||
}
|
||||
|
||||
void close() {
|
||||
assertNotNull(this->file);
|
||||
fclose(this->file);
|
||||
}
|
||||
|
||||
bool_t readString(std::string *out) {
|
||||
assertNotNull(out);
|
||||
|
||||
if(!this->isOpen()) {
|
||||
if(!this->open(FILE_MODE_READ)) return false;
|
||||
}
|
||||
assertTrue(this->mode == FILE_MODE_READ);
|
||||
out->clear();
|
||||
|
||||
size_t i = 0;
|
||||
char buffer[FILE_BUFFER_SIZE + 1];
|
||||
while(i != this->length) {
|
||||
size_t amt = mathMin<size_t>(FILE_BUFFER_SIZE, (this->length - i));
|
||||
auto amtRead = fread(buffer, sizeof(char), amt, this->file);
|
||||
if(amtRead != amt) return false;
|
||||
i += amtRead;
|
||||
buffer[amtRead + 1] = '\0';
|
||||
out->append(buffer);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool_t mkdirp() {
|
||||
fileMkdirp((char *)this->filename.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool_t writeString(std::string in) {
|
||||
if(!this->isOpen()) {
|
||||
if(!this->open(FILE_MODE_WRITE)) return false;
|
||||
}
|
||||
assertTrue(this->mode == FILE_MODE_WRITE);
|
||||
|
||||
const char_t *strOut = in.c_str();
|
||||
// TODO: Validate write length.
|
||||
fwrite(strOut, sizeof(char_t), in.size(), this->file);
|
||||
return true;
|
||||
}
|
||||
|
||||
~File() {
|
||||
if(this->file != nullptr) this->close();
|
||||
}
|
||||
};
|
||||
}
|
Reference in New Issue
Block a user