Debug class
Posted: Mon May 31, 2010 4:30 pm
edit: thanks to xeno for pointing out the vsnprintf function to me, and X abstract X for pointing out the =operator and copy constructor to me.
Hey guys, I decided that my old debug class wasn't good enough so I looked into how printf worked and discovered variadic functions. This is my first time using them, but I was hoping I could get some feedback.
Code: Select all
/*
* Debug.h
* XCODE SFML_ENGINE
*
* Created by Benjamin Adamson on 5/31/10.
* Copyright 2010 Oregon State University. All rights reserved.
*
*/
#define dbg Debug::get_Instance()
#include <string>
#include <fstream>
#include <assert.h>
#include <stdio.h>
#ifndef _DEBUG_H_
#define _DEBUG_H_
class Debug
{
private:
Debug(const Debug& d); // copy constructor needs to be private as well.
Debug();
~Debug();
// member variables
const static unsigned int m_sizebuffer = 1028;
std::ofstream m_file;
bool m_fileopened;
char m_buffer[m_sizebuffer];
va_list m_vl;
//=operator needs to be private
Debug& operator=(const Debug &rhs)
{
}
public:
static inline Debug &get_Instance()
{
static Debug instance;
return instance;
}
void open_file(const std::string& filename);
void print(const std::string& fmt, ...);
};
#endif // End include guard.
Code: Select all
/*
* Debug.cpp
* XCODE SFML_ENGINE
*
* Created by Benjamin Adamson on 5/31/10.
* Copyright 2010 Oregon State University. All rights reserved.
*
*/
#ifndef _DEBUG_H_
#include "Debug.h"
#endif
Debug::Debug()
{
}
Debug::~Debug()
{
if(m_fileopened)
{
m_file.close();
}
}
void Debug::open_file(const std::string& filename)
{
// file cannot already be opened.
assert(!m_fileopened);
m_file.clear(); // clear contents of debug file.
m_file.open(filename.c_str());
if(m_file.is_open() )
{
m_fileopened = true;
dbg.print("Debug: successfully loaded file '%s'.\n", filename.c_str() );
}
else
{
// file failed to open
dbg.print("Debug: failed to open file '%s'.\n", filename.c_str() );
}
}
/*
WARNING: Should only accept c-style strings only. If output is ever cryptic double check
that we are not passing c++ Strings instead of char*, do not know how to differentiate if
fmt is a c-style string (char*) or a C++ String.
*/
void Debug::print(const std::string& fmt, ...)
{
// cannot print unless a file is opened.
assert(m_fileopened);
va_start(m_vl, fmt);
vsnprintf(m_buffer, m_sizebuffer, fmt.c_str(), m_vl);
va_end(m_vl);
m_file << m_buffer;
m_file.flush();
}