6 #include <hal_posix/file_io.h>
19 FileWriter::FileWriter(
const char* filename,
bool close_on_finalize)
20 : m_close_on_finalize(close_on_finalize)
25 if (filename)
open(filename);
28 FileWriter::~FileWriter()
37 if (filename) m_file = fopen(filename,
"wb");
40 void FileWriter::close()
43 if (m_file) fclose(m_file);
50 if (m_file) fseek(m_file, m_last_commit + offset, SEEK_SET);
56 return m_file ? UINT32_MAX : 0;
61 if (m_file) fwrite(src, 1, nbytes, m_file);
67 if (m_file) m_last_commit = (unsigned)ftell(m_file);
68 if (m_close_on_finalize) close();
77 _chsize(fileno(m_file), m_last_commit);
79 ftruncate(fileno(m_file), m_last_commit);
81 fseek(m_file, m_last_commit, SEEK_SET);
86 if (m_file) fputc(data, m_file);
90 : m_close_on_finalize(close_on_finalize)
95 if (filename)
open(filename);
98 FileReader::~FileReader()
107 if (filename) m_file = fopen(filename,
"rb");
113 fseek(m_file, 0, SEEK_END);
114 m_rem = (unsigned)ftell(m_file);
115 fseek(m_file, 0, SEEK_SET);
119 void FileReader::close()
122 if (m_file) fclose(m_file);
129 return m_file ? m_rem : 0;
135 if (m_file && m_rem >= nbytes) {
136 result = fread(dst, 1, nbytes, m_file);
139 return (result == nbytes);
144 if (m_file && m_rem >= nbytes) {
145 fseek(m_file, (
int)nbytes, SEEK_CUR);
156 if (m_close_on_finalize) close();
161 if (m_file && m_rem) {
163 return (u8)fgetc(m_file);
Read bytes or packets from a file.
FileReader(const char *filename=0, bool close_on_finalize=false)
Create the FileWriter object.
void read_finalize() override
Consume any remaining bytes in this frame, if applicable.
void open(const char *filename, unsigned len=0)
Open the specified file to read the next frame.
bool read_bytes(unsigned nbytes, void *dst)
Read 0 or more bytes into a buffer.
unsigned get_read_ready() const override
How many bytes can be read without blocking?
bool read_consume(unsigned nbytes)
Read and discard 0 or more bytes.
u8 read_next() override
Read the next byte from the underlying buffer or device.
Write bytes or packets to a file.
unsigned get_write_space() const override
How many bytes can be written without blocking?
void write_bytes(unsigned nbytes, const void *src)
Write 0 or more bytes from a buffer.
void write_abort() override
If possible, abort the current partially-written packet.
bool write_finalize() override
Mark end of frame and release temporary working data.
void write_next(u8 data) override
Write the next byte to the underlying buffer or device.
void open(const char *filename)
Open the specified file.
void seek(unsigned offset)
Move write cursor to the specified absolute offset.
Miscellaneous POSIX wrappers (e.g., heap allocation, log to console...)