rexylib/rexy/filerd.cpp
2020-03-02 16:35:52 -08:00

113 lines
2.7 KiB
C++

/**
This file is a part of rexy's general purpose library
Copyright (C) 2020 rexy712
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "filerd.hpp"
#include <cstdio> //fopen, fclose
#include <utility> //exchange, swap
namespace rexy{
filerd::filerd(const char* f, const char* mode):
m_fp(fopen(f, mode)){}
filerd::filerd(filerd&& f):
m_fp(std::exchange(f.m_fp, nullptr)){}
filerd::~filerd(void){
if(m_fp)
fclose(m_fp);
}
filerd& filerd::operator=(filerd&& f){
std::swap(m_fp, f.m_fp);
return *this;
}
void filerd::reset(FILE* fp){
if(m_fp)
fclose(m_fp);
m_fp = fp;
}
FILE* filerd::release(void){
return std::exchange(m_fp, nullptr);
}
size_t filerd::length(void){
if(!m_fp)
return 0;
size_t tmp, ret;
tmp = ftell(m_fp);
fseek(m_fp, 0, SEEK_END);
ret = ftell(m_fp);
fseek(m_fp, tmp, SEEK_SET);
return ret;
}
size_t filerd::position(void)const{
return ftell(m_fp);
}
void filerd::rewind(size_t pos){
fseek(m_fp, pos, SEEK_SET);
}
filerd::operator FILE*(void){
return m_fp;
}
filerd::operator const FILE*(void)const{
return m_fp;
}
FILE* filerd::get(void){
return m_fp;
}
const FILE* filerd::get(void)const{
return m_fp;
}
filerd::operator bool(void)const{
return m_fp;
}
size_t filerd::read(char* dest, size_t bytes){
return fread(dest, 1, bytes, m_fp);
}
rexy::string filerd::read(size_t bytes){
char* tmp = reinterpret_cast<char*>(rexy::string::allocator_type::allocate(bytes));
size_t written = read(tmp, bytes);
return rexy::string(tmp, written);
}
rexy::string filerd::readln(size_t max){
rexy::string ret;
char c;
size_t count = 0;
for(c = fgetc(m_fp);c != EOF && c != '\n';c = fgetc(m_fp)){
ret.append(&c, 1);
if(++count == max)
break;
}
return ret;
}
rexy::binary filerd::read_bin(size_t bytes){
char* tmp = reinterpret_cast<char*>(rexy::binary::allocator_type::allocate(bytes));
size_t written = read(tmp, bytes);
return rexy::binary(tmp, written, written);
}
size_t filerd::write(const char* c, size_t bytes){
return fwrite(c, 1, bytes, m_fp);
}
size_t filerd::write(const rexy::string_base& c){
return write(c.get(), c.length());
}
}