log.h文件:
#include
#include
#include
#include
#include
#include
FILE *open_log(char *filename);
void write_log( FILE *filep, const char *fmt,...);
int close_log(FILE *fp);
log.c文件:
/*Function:获取当前系统时间
* Input: iosec 保存当前时间的数字格式
* Output: curtime 当前时间存放地址
* Return:当前时间的字符串
*/
const char *getcurdate(char *curtime)
{
int TIME_LEN = 50;
time_t rawtime;
struct tm *tm_local;
rawtime = time((time_t *)NULL);
tm_local = localtime(&rawtime);
memset(curtime, '\0', sizeof(curtime));
sprintf(curtime, "%4d-%02d-%02d %02d:%02d:%02d ", 1900+tm_local->tm_year, 1+tm_local->tm_mon, tm_local->tm_mday, tm_local->tm_hour, tm_local->tm_min, tm_local->tm_sec);
return curtime;
}
/*Function:打开日志文件
* Input: filename 日志文件名
* Return:日志文件指针
*/
FILE *open_log(char *filename)
{
FILE *fp;
if((fp = fopen(filename,"a+")) == NULL)
{
perror("fopen");
return NULL;
}
return fp;
}
/* Function:写日志
* Input:inLogInfo--日志对象, fmt--日志内容的格式串
* Output:
* Return:
*/
void write_log( FILE *fp, const char *fmt,...)
{
int LOG_LEN = 256, TIME_LEN = 50;
char buffer[LOG_LEN], curtime[TIME_LEN];
memset(buffer,'\0', sizeof(buffer));
memset(curtime,'\0', sizeof(curtime));
getcurdate(curtime);
strncpy(buffer, curtime, strlen(curtime));
va_list ap;
va_start(ap, fmt);
vsnprintf( buffer+strlen(curtime), LOG_LEN-1, fmt, ap);
va_end(ap);
printf("%s", buffer);
if(fputs(buffer,fp) == EOF)
perror("fputs");
}
/*Function:打开日志文件
* Input: filename 日志文件名
* Return:日志文件指针
*/
int close_log(FILE *fp)
{
if(fclose(fp) == EOF)
{
perror("fclose");
return -1;
}
return 0;
}
阅读(770) | 评论(0) | 转发(0) |