- 代码
- 输出结果
#include输出结果#include #include #include #include FILE* fp = NULL; char *get_cur_time() { static char s[32] = {0}; time_t t; struct tm* ltime; struct timeval stamp; gettimeofday(&stamp, NULL); ltime = localtime(&stamp.tv_sec); s[0] = '['; strftime(&s[1], 20, "%Y-%m-%d %H:%M:%S", ltime); sprintf(&s[strlen(s)], ".%03ld]", (stamp.tv_usec/1000)); return s; } #define PRINT(str, fmt, ...) printf("%s %s "fmt"n", get_cur_time(), str, ##__VA_ARGS__);fflush(fp) int main(void) { int i = 0; if(0 == (fp = freopen("./my.log", "a", stdout))) { printf("Cannot open file.n"); } while (1) { PRINT("log","hello world"); usleep(100000); } }
编译执行以上代码,生成my.log文件,打开文件,如图:



