1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| //fichier convertingStrings.h (nécessaire pour convertire une wstring en string):
#include <string>
const std::wstring StringToWString (const std::string& s)
{
std::wstring temp (s.length (), L' ');
std::copy (s.begin (), s.end (), temp.begin ());
return temp;
}
const std::string WStringToString (const std::wstring& s)
{
std::string temp (s.length (), ' ');
std::copy (s.begin (), s.end (), temp.begin ());
return temp;
}
---------------------
fichier Log.h
#include <fstream>
#include <string>
#include <iostream>
class Log
{
public:
// La commande pour imprimer le texte.
void Print (const std::wstring& wtext, const std::string& text);
// La fonction pour ouvrir un fichier.
static void Open (const std::wstring& wfilename, const std::string& filename);
// Les fonctions d'accès pour recevoir une référence ou un pointeur sur l'unique instance de cette classe.
static Log& Reference ();
static Log* Pointer () { return &Reference (); }
private:
// Constructeur et destructeur
Log () {}
~Log () {}
// Interdit la construction par copie et l'assignation
Log& operator= (Log&);
Log (const Log&);
std::wofstream wout; // Le flux de sortie sur lequel écrire.
std::ofstream out;
};
-----------------
fichier log.cpp
#include "Log.h"
#include "ConvertingStrings.h"
// La fonction statique pour ouvrir un fichier.
void Log::Open (const std::wstring& wfilename, const std::string& filename)
{
Log& log = Reference ();
log.wout.open (WStringToString (wfilename).c_str ());
log.out.open (filename.c_str ());
}
// La fonction statique pour obtenir une référence sur la seule instance de cette classe.
Log& Log::Reference ()
{
static Log log;
return log;
}
// La fonction pour écrire sur le flux
void Log::Print (const std::wstring& wtext, const std::string& text)
{
wout << wtext << std::endl;
out << text << std::endl;
}
--------------------
Main.cpp:
#include "Log.h"
int main (int argc, char *argv[])
{
Log::Open (L"Wessai.txt", "essai.txt");
Log::Reference().Print (L"Appellée dans main à partir de la référence.", "Appellée dans main à partir de la référence.");
Log::Pointer()->Print (L"Appellée dans main à partir du pointeur.", "Appellée dans main à partir du pointeur.");
return 0;
} |
Partager