When an error occurs in the code, you need to write the error to the log file. When writing the error, you also need to write the current time. The following code is a small instance.
1 #include <iostream> 2 #include <fstream> 3 #include <ctime> 4 5 using namespace std; 6 7 int main(int argc, char **argv) 8 { 9 ofstream fout("test.log", ios::out | ios::app);10 if(!fout.is_open())11 {12 cout << "Open log file failed" << endl;13 return 0;14 }15 16 // 写入日志17 time_t timer;18 struct tm *pstTime;19 timer = time(NULL);20 pstTime = localtime(&timer);21 22 fout << asctime(pstTime) << endl;23 fout << "Errno : " << 3 << endl;24 fout << "Error : " << "hh" << endl;25 fout << endl << endl;26 27 return 0;28 }
A simple usage code of the time function is provided.
1 #include <cstdio> 2 #include <ctime> 3 4 using namespace std; 5 6 int main(int argc, char **argv) 7 { 8 time_t timer; 9 struct tm *pstTime;10 11 timer = time(NULL);12 pstTime = localtime(&timer);13 14 printf("Local time is:%s \n", asctime(pstTime));15 printf("Local time is:%s \n", ctime(&timer));16 17 return 0;18 }
Output Current Time in Log File