1
0
Fork 0

Adding Spectre/System/Log/FileWriter class.

This commit is contained in:
Henrik Hautakoski 2023-02-18 13:52:54 +01:00
parent 173aea31c9
commit 8db01a0957
3 changed files with 97 additions and 0 deletions

View file

@ -21,6 +21,7 @@ set( ENGINE_SRC
source/System/MessageQueue.cpp
source/System/Path.cpp
source/System/Stopwatch.cpp
source/System/Log/FileWriter.cpp
# Platform
source/Platform/PlatformApplication.cpp

View file

@ -0,0 +1,30 @@
#ifndef SPECTRE_SYSTEM_LOG_FILEWRITER_H
#define SPECTRE_SYSTEM_LOG_FILEWRITER_H
#include <stdio.h>
#include <string>
#include <Spectre/System/Log/Writer.h>
namespace sp { namespace log {
class FileWriter : public Writer
{
public:
FileWriter(const std::string file = "");
~FileWriter();
bool open(const std::string file);
bool close();
size_t write(const void *data, size_t len);
protected:
FILE *m_fd;
};
} } // sp::log
#endif /* SPECTRE_SYSTEM_LOG_FILEWRITER_H */

View file

@ -0,0 +1,66 @@
#include <Spectre/System/Log/FileWriter.h>
namespace sp { namespace log {
FileWriter::FileWriter(const std::string file) :
m_fd (NULL)
{
if (file.length() > 0) {
open(file);
}
}
FileWriter::~FileWriter()
{
if (m_fd) {
close();
}
}
bool FileWriter::open(const std::string file)
{
if (!close()) {
return false;
}
if (file == "stderr") {
m_fd = stderr;
return true;
}
if (file == "stdout") {
m_fd = stdout;
return true;
}
m_fd = fopen(file.c_str(), "a");
if (m_fd == NULL) {
return false;
}
return true;
}
bool FileWriter::close()
{
if (m_fd) {
// stdout and stderr can not be closed.
if (m_fd == stdout || m_fd == stderr) {
m_fd = NULL;
return true;
}
if (fclose(m_fd) < 0) {
return false;
}
m_fd = NULL;
}
return true;
}
size_t FileWriter::write(const void *data, size_t len)
{
return fwrite(data, 1, len, m_fd);
}
} } // sp::log