blog/cpp/fonts/reader/file.cpp

174 lines
2.9 KiB
C++

#include "file.h"
#include <cstring>
#include <sstream>
#include <endian.h>
file::file(const char *filePath) : reader()
{
fp.open(filePath, std::ios::binary);
if (!fp.is_open())
{
throw "file now open";
}
path = new char[std::strlen(filePath)];
std::memcpy(path, filePath, std::strlen(filePath));
fp.seekg(0, fp.end);
length = fp.tellg();
fp.seekg(0, fp.beg);
};
std::streamsize file::read(char *bytes, uint16_t l)
{
fp.read(bytes, l);
std::streamsize bytesRead = fp.gcount();
return bytesRead;
};
int8_t file::readInt8()
{
int8_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe16(ret);
}
int16_t file::readInt16()
{
int16_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe16(ret);
};
int32_t file::readInt32()
{
int32_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe16(ret);
}
int64_t file::readInt64()
{
uint64_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe16(ret);
}
uint8_t file::readUint8()
{
uint8_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return ret;
}
uint16_t file::readUint16()
{
uint16_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe16(ret);
};
uint24_t file::readUint24()
{
uint24_t ret(0);
fp >> ret;
return ret;
}
uint32_t file::readUint32()
{
uint32_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe32(ret);
}
uint64_t file::readUint64()
{
uint64_t ret = 0;
fp.read(reinterpret_cast<char *>(&ret), sizeof(ret));
return htobe64(ret);
}
std::string file::readString(int l)
{
char *data = new char[l];
fp.read(data, l);
std::streamsize bytesRead = fp.gcount();
auto ret = std::string(data, bytesRead);
delete[] data;
return ret;
}
FWORD file::readFWord(){
return readInt16();
}
UFWORD file::readUFWord(){
return readUint16();
}
Offset8 file::readOffset8(){
return readUint8();
}
Offset16 file::readOffset16(){
return readUint16();
}
Offset24 file::readOffset24(){
return readUint24();
}
Offset32 file::readOffset32(){
return readUint32();
}
int24_t file::readInt24(){
int24_t i;
fp>>i;
return i;
}
Fixed file::readFixed(){
Fixed f;
fp>>f;
return f;
}
F2DOT14 file::readF2Dot14(){
F2DOT14 f;
fp>>f;
return f;
}
Version16Dot16 file::readVersion16Dot16(){
Version16Dot16 v;
fp>>v;
return v;
}
Tag file::readTag(){
Tag t;
fp>>t;
return t;
}
bool file::seek(int64_t i)
{
if (i > length)
{
return false;
}
fp.seekg(i);
return true;
}
std::streampos file::curr()
{
return fp.tellg();
}
std::string file::getPath()
{
return path;
}
file::~file()
{
if (fp.is_open())
{
fp.close();
}
if (path != nullptr)
{
delete path;
}
}