user1165435
user1165435

Reputation: 231

how to create logfiles in c++

I need to create a logfile. I don't know what errors do have to put in the logfile. I have the following code (but I don't know why is not writting to the end of a file)

log.cpp

#include "log.h"
#include <ctime>
#include <iostream>
using namespace std;
Log::Log(char* filename) {
//ofstream m_stream(filename);
m_stream.open(filename);

}

In a test.cpp I have pLOg->Write(c). I don't understand why is rewritting the file and why is not writting at te enf of it.

void Log::Write(char* logline)
{
time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  m_stream.seekp (0, ios::end); 
  while ((m_stream.eof())){}
  {
  m_stream <<"current time: "<< asctime (timeinfo) <<" "<< logline << endl;
  }

}

Log::~Log(){

  m_stream.close();
}

log.h

#include <fstream>

using namespace std;

class Log {
  public:
    Log(char* filename);
    ~Log();
    void Write(char* logline);
private:
    ofstream m_stream;
};

Upvotes: 1

Views: 690

Answers (2)

Tejas Patil
Tejas Patil

Reputation: 6169

Change the constructor to:

Log::Log(char* filename) {
    m_stream.open(filename, std::ios::out | std::ios::app);
}

More explanation: http://en.allexperts.com/q/C-1040/apped-data-enf-text.htm

Upvotes: 0

Duck
Duck

Reputation: 27572

m_stream.open(filename, ios_base::app | ios_base::out);

Upvotes: 3

Related Questions