您的位置:首页 > 其它

用C实现日志文件的记录

2011-11-03 14:42 357 查看
#include <stdio.h>

#include <time.h>

#include <string.h>

#include <errno.h>

/*宏定义参数*/

#define RecordLogFile(ONE, TWO) defineRecordLogFile(__FILE__, __LINE__, ONE, TWO)

int defineRecordLogFile(char *pszMyFileName, int iLine,\

char *pszMyErroe, const char *pszLogFileName);

int main(int argc, char *argv[])

{

if (argc < 2)

{

RecordLogFile("我自己的输出错误!", "liujie.log");

return 1;

}

return 0;

}

int defineRecordLogFile(char *pszMyFileName, int iLine,\

char *pszMyError, const char *pszLogFileName)

{

FILE *fpLogFile;

time_t timeTemp;

struct tm *pstTime;

pid_t pidMyId;

char szNewLogFileName[64 + 1];

char szSystem[128 + 1];

char szTime[19 + 1];

/*打开文件*/

if ((fpLogFile = fopen(pszLogFileName, "a")) == NULL)

{

printf("open LogFile faile!");

RecordLogFile("open LogFile faile!", "liujie.log");

return 1;

}

/*时间*/

timeTemp = time(NULL);

pstTime = localtime(&timeTemp);

sprintf(szTime, "%2.2d-%2.2d-%2.2d-%2.2d:%2.2d:%2.2d ",\

pstTime->tm_year + 1900,pstTime->tm_mon + 1,\

pstTime->tm_mday,pstTime->tm_hour,pstTime->tm_min,\

pstTime->tm_sec);

fprintf(fpLogFile, szTime);

/*得到文件ID*/

pidMyId = getpid();

fprintf(fpLogFile, "pid = %d ", pidMyId);

/*得到文件位置*/

fprintf(fpLogFile, "%s:%d ", pszMyFileName, iLine);

/*得到错误信息*/

fprintf(fpLogFile, "useerror: %s ", pszMyError);

fprintf(fpLogFile, "error: %s\n", strerror(errno));

/*关闭文件*/

fclose(fpLogFile);

/*调用system实现拷贝*/

memset(szSystem, 0, 128 + 1);

memset(szNewLogFileName, 0, 64 + 1);

/*得到新配置文件名*/

strncpy(szNewLogFileName, pszLogFileName, 64 - 19);

strncat(szNewLogFileName, szTime, 19);

/*得到system参数*/

strncpy(szSystem, "cp ", 3);

strncat(szSystem, pszLogFileName, 64);

strncat(szSystem, " ", 1);

strncat(szSystem, szNewLogFileName, 64);

system(szSystem);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: