To write execution results in a txt file....

I want to store the intermediate results in text files.
Requirements:
- file can be open with in different classes and functions of my Project
- results should be in the same order

Problem:

In the project there are several classes, functions and .cpp files, so what is the best way (program design) to place
-the file declaration
- file open function
- and to close the file

There are several function calls.

Thanks in advance for your guidance.
Use a singleton.

logger.h
1
2
3
4
5
6
#ifndef LOGGER_H
#define LOGGER_H
  
class Logger {/*...*/};

#endif 

logger.cpp
1
2
3
4
5
#include "logger.h"

//implementation of the Logger class

//... 

source_file_x.cpp
1
2
3
4
5
6
7
#include "logger.h"

//...

Logger::GetInstance().Log(/*...*/);

//... 

Useful link -> http://www.devarticles.com/c/a/Cplusplus/C-plus-plus-In-Theory-The-Singleton-Pattern-Part-I/
Last edited on
And inside Log(), add a lock for the writing to the file in case you call Log() from multiple threads.

Also, if you access the file with FILE* stuff, yo can use setvbuff to set the write buffer to 0, so everything is written immediately and you don't lose the last mesages in case the program crashes

For my own Log function, i used a static method instead of a singleton method, i don't think a singleton brings more benefits than a static method in that case, and Logger::log() is simpler to write.
Topic archived. No new replies allowed.