#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/shm.h>
#include <sys/file.h>
#include <wait.h>
#include <stdlib.h>
#include <time.h>
#include <stdarg.h>
#define LOG "./log"
void log(char CH,const char* format,...)
{
time_t t;
struct tm* p;
int r,fd;
FILE* fp;
va_list ap;
t = time(NULL);
p = gmtime(&t); //当前时间
fp = fopen(LOG,"a");
if(fp == NULL)
{
fprintf(stderr,"Unable to open '%s'.\n",LOG);
return;
}
fd = fileno(fp);
r = flock(fd,LOCK_EX); //给文件加锁
if(r != 0)
perror("File lock error.\n");
fprintf(fp,"[%i/%02i/%02i %02i:%02i:%02i]: ",1900+p->tm_year,1+p->tm_mon,p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec); //记录时间
switch(CH)
{
case 'A':
fprintf(fp,"very good: ");
break;
case 'B':
fprintf(fp,"good: ");
break;
case 'C':
fprintf(fp,"same: ");
break;
case 'D':
fprintf(fp,"error: ");
default:
break;
}
va_start(ap,format); //获取参数量
vfprintf(fp,format,ap); //打印到文件
va_end(ap);
fprintf(fp,"\n");
r = flock(fd,LOCK_UN); //解锁
if(r != 0)
perror("Ulock error.\n");
fclose(fp);
}
int main()
{
char *A1="70-90";
char *A2="90-100";
log('A',"%s,%s",A1,A2);
log('B',"60-70");
log('C',"40-60");
log('D',"30-40");
return 0;
}
|