求LINUX下,C语言编写的日志输出源码~

条件: A、 日志的输出格式为:[2013-04-17 12:23:17] [DEBUG] file no find B、 日志文件在超过1K大小后,自动新建一个日志文件。 C、 当日志文件超过10个后,自动从第一个日志文件重新记录。
发觉问的好傻...求参考资料也可以~我错了

#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,"\r\n");
    strcpy(logFileName,LOGFILE);
    int len = strlen(logFileName);
    logFileName[len-1] = '0'+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] = '0';
                g_Count=0;
            }
            else
            {
                g_Count++;
                logFileName[len-1] = '0'+g_Count;
            //  printf("\n%c",'0'+g_Count);
            }
            fp = fopen(logFileName,"w+");
        }
        else
        { 
            fclose(fp);
            fp = fopen(logFileName,"a");
        }
    }
    fwrite(buf,1,strlen(buf),fp);
    fclose(fp);
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-10
这个我只是建议,因为我不知道你想写个给什么用的日志程序,输入从哪里来...
用Linux的系统调用,#include <unistd.h>、<stdlib.h> 以及<time.h>,调用time(time_t *)获得时间,至于确定大小,用管道,调用pipe(int []),将buf定为char buf[1000],将标准输出关闭,再将输入流重定向至管道,用dup()系统调用将描述符复制过来,然后通过循环调用read()和write()系统调用,读写数据,剩下的就是文件计数的问题了。
第2个回答  2013-05-10
没明白题目什么意思.
相似回答