㈠ c語言如何實現日誌文件裡面只保留最近500條消息,超過的就自動刪除掉
日誌文件每日內容前加入時間戳
建立臨時文件
從相應時間戳開始讀取內容寫入臨時文件
刪除原文件,臨時文件更名
㈡ 求LINUX下,C語言編寫的日誌輸出源碼~
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include <time.h>
#define LOGFILE "./dir_log_0"
int g_Count;
//#define MAXLEN 1024
void WriteDebugLog(char *str);
int main(int argc, char **argv)
{
char str[1024]={0};
strcpy(str,"file no find");
int i=0,j=0;
for (i=0; i<10; i++)
{
for (j=0; j<50; j++)
{
WriteDebugLog(str);
}
}
return 0;
}
void WriteDebugLog(char *str)
{
char buf[2048]={0};
char logFileName[50]={0};
//long MAXLEN = 50*1024*1024;//50MB
int iMax = 1024;//1K
time_t timep;
FILE *fp = NULL;
struct tm *p;
time(&timep);
p = localtime(&timep);
memset(buf,0,sizeof(buf));
sprintf(buf,"[%d-%d-%d %d:%d:%d][DEBUG]",(1900+p->tm_year),(1+p->tm_mon), p->tm_mday,p->tm_hour, p->tm_min, p->tm_sec); //星期p->tm_wday
strcat(buf,str);
strcat(buf," ");
strcpy(logFileName,LOGFILE);
int len = strlen(logFileName);
logFileName[len-1] = Ɔ'+g_Count;
fp = fopen(logFileName,"r");
if(fp==NULL)
{
fp = fopen(logFileName,"w+");
}
else
{
fseek(fp,0,2);//SEEK_END值為2
if( ftell(fp) >= iMax)
{
fclose(fp);
if (g_Count >= 9)
{
logFileName[len-1] = Ɔ'
g_Count=0;
}
else
{
g_Count++;
logFileName[len-1] = Ɔ'+g_Count;
// printf(" %c",Ɔ'+g_Count);
}
fp = fopen(logFileName,"w+");
}
else
{
fclose(fp);
fp = fopen(logFileName,"a");
}
}
fwrite(buf,1,strlen(buf),fp);
fclose(fp);
}