首页
登录 | 注册

C写日志文件

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<stdarg.h>
void logfile(const char *fmt,...);

 

int main()
{
 logfile("%s","login system");
 return 0;
}

 

void logfile(const char *fmt,...)
{
 FILE *fp;
 char buffer[512];
 char *p;
 time_t t;
 va_list ap;
 va_start(ap,fmt);
 vsprintf(buffer,fmt,ap);
 va_end(ap);
 if((fp=fopen("file.log","a+"))==NULL)
 {
  printf("open logfile failed\n");
  exit(0);
 }
 time(&t);
 p=ctime(&t);
 p[strlen(p)-1]='\0';//去除时间后的回车
 fprintf(fp,"[%s] %s \n",p,buffer);
 fclose(fp);
}

 

 

 

生成

Fri Jan 11 22:33:02 2013 login system
Fri Jan 11 22:33:18 2013 login system
Fri Jan 11 22:37:47 2013 login system
Fri Jan 11 22:37:56 2013 login system
Sat Jan 12 17:50:47 2013 login system
Sun Jan 13 21:56:11 2013 login system 5
[Mon Jan 14 13:18:39 2013]login system
[Mon Jan 14 13:19:59 2013
]login system
[Mon Jan 14 13:28:12 2013] login system
[Mon Jan 14 13:28:31 2013] login system
[Mon Jan 14 13:28:56 2013] login system
[Mon Jan 14 13:28:58 2013] login system



2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.009 s.
京ICP备10005923号