begin implementing FileReader

This commit is contained in:
Josh Holtrop 2014-06-04 22:09:57 -04:00
parent 9abd4ef04b
commit af5df42bbc
2 changed files with 85 additions and 0 deletions

View File

@ -2,14 +2,24 @@
#define JES_FILEREADER_H
#include "jes/Ref.h"
#include "jes/Text.h"
#include <stdint.h>
namespace jes
{
class FileReader
{
public:
FileReader();
~FileReader();
bool load(const char * fname);
void close();
unsigned int num_lines() { return m_num_lines; }
TextRef get_line(unsigned int line_no);
protected:
int m_fd;
unsigned int m_num_lines;
uint8_t * m_buf;
};
typedef Ref<FileReader> FileReaderRef;
}

View File

@ -1 +1,76 @@
#include "jes/FileReader.h"
#include "jes/Text.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
namespace jes
{
FileReader::FileReader()
{
m_fd = 0;
m_num_lines = 0u;
m_buf = NULL;
}
FileReader::~FileReader()
{
close();
}
bool FileReader::load(const char * fname)
{
struct stat st;
if (stat(fname, &st) != 0)
{
return false;
}
if (st.st_size < 0)
{
return false;
}
if (st.st_size == 0)
{
return true;
}
m_fd = open(fname, O_RDONLY);
if (m_fd < 0)
{
return false;
}
m_buf = new uint8_t[st.st_size];
if (read(m_fd, m_buf, st.st_size) != st.st_size)
{
m_buf = NULL;
delete[] m_buf;
return false;
}
return true;
}
void FileReader::close()
{
if (m_buf != NULL)
{
delete[] m_buf;
m_buf = NULL;
}
if (m_fd != 0)
{
::close(m_fd);
m_fd = 0;
}
}
TextRef FileReader::get_line(unsigned int line_no)
{
}
}