C++有四个常用的预定义名字,分别为:__FILE__,__LINE__,__DATE__,__TIME__
__FILE__:记录文件的路径加名称
__LINE__:记录文件已经被编译的行数
__DATE__:记录文件的编译日期
__TIME__:记录文件的编译时间
可以当作变量直接使用,一般用作程序调试
例子:
#include <iostream>
using namespace std;
int main()
{
cout << "File = " << __FILE__ << ‘\n‘
<< "LINE = " << __LINE__ << ‘\n‘
<< "DATE = " << __DATE__ << ‘\n‘
<< "TIME = " << __TIME__
<< endl;
getchar();
}
运行结果:
File = G:/program/study/c++/test1.cpp
LINE = 17
DATE = May 27 2004
TIME = 09:59:01
用于打印日志、调试非常方便
下面函数是把__DATE__宏转换成 time_t的时间类型,便于进行操作
static time_t getDateFromMacro(char const *time) {
char s_month[5];
int month, day, year;
struct tm t = {0};
static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
sscanf(time, "%s %d %d", s_month, &day, &year); month = (strstr(month_names, s_month)-month_names)/3;
t.tm_mon = month;
t.tm_mday = day;
t.tm_year = year - 1900;
t.tm_isdst = -1;
return mktime(&t);
}