Source

pyGAP / game / engine / io / file / stdio.cpp

Full commit
#include "io/file/base.h"
#include "io/file/stdio.h"


namespace io { namespace file {


Stdio::Stdio() : file_(NULL) {

}


Stdio::~Stdio() {
    close();
    file_ = NULL;
}


bool Stdio::open(const char* filename, const char* mode) {
    file_ = fopen(filename, mode);
    return is_open();
}


bool Stdio::is_open() const {
    return file_ != NULL;
}


void Stdio::close() {
    if (!is_open())
        return;
    fclose(file_);
    file_ = NULL;
}


void Stdio::seek(uint64_t offset) {
    if (!is_open())
        return;
    fseek(file_, offset, SEEK_SET);
}


uint64_t Stdio::tell() const {
    if (!is_open())
        return -1;
    return ftell(file_);
}


size_t Stdio::read(uint8_t* buffer, size_t size, size_t count) {
    if (!is_open())
        return -1;
    return fread(buffer, size, count, file_);
}


size_t Stdio::write(const uint8_t* buffer, size_t size, size_t count) {
    if (!is_open())
        return -1;
    return fwrite(buffer, size, count, file_);
}


size_t Stdio::size() {
    if (!is_open())
        return -1;

    size_t size = 0;
    uint64_t offset = tell();

    fseek(file_, 0, SEEK_END);
    size = tell();
    seek(offset);

    return size;
}


uint8_t* Stdio::read() {
    if (!is_open())
        return NULL;

    size_t buf_size = size();
    uint8_t* buffer = new uint8_t [buf_size];

    read(buffer, sizeof(uint8_t), buf_size);

    return buffer;
}


} /* namespace file */ } /* namespace io */