项目中加入Error Log日志

本文介绍了一个简单的错误日志系统实现,包括错误文件的打开、关闭及错误信息的写入等功能。该系统通过全局变量管理错误文件句柄,并提供了一系列实用的函数来方便地记录和管理错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 全局变量
extern FILE *fp_error;					// general error file;                          
extern char error_filename[256];                  // error file name
int Write_Error(char *string, ...);
int Open_Error_File(char *filename, FILE *fp_override);
int Close_Error_File(void);
FILE *fp_error = NULL;					// general error file;                          
char error_filename[256] = "你的错误日志文件名.txt";                  // error file name
//错误Log输出
///////////////////////////////////////////////////////////
int Write_Error(char *string, ...)
{
	// this function prints out the error string to the error file

	char buffer[256]; // working buffer

	va_list arglist; // variable argument list

	// make sure both the error file and string are valid
	if (!string || !fp_error)
		return(0);

	// print out the string using the variable number of arguments on stack
	va_start(arglist,string);
	vsprintf(buffer,string,arglist);
	va_end(arglist);

	// write string to file
	fprintf(fp_error,buffer);

	// flush buffer incase the system bails
	fflush(fp_error);

	// return success
	return(1);
} // end Write_Error

///////////////////////////////////////////////////////////////////////////////

int Open_Error_File(char *filename, FILE *fp_override = NULL)
{
// this function creates the output error file

// is user requesting special file handle? stdout, stderr, etc.?
if (fp_override)
{
fp_error = fp_override;
}
else
{
// test if this file is valid
if ((fp_error = fopen(filename,"w"))==NULL)
   return(0);
}

// get the current time
struct _timeb timebuffer;
char *timeline;
char timestring[280];

_ftime(&timebuffer);
timeline = ctime(&(timebuffer.time));

sprintf(timestring, "%.19s.%hu, %s", timeline, timebuffer.millitm, &timeline[20]);

// write out error header with time
Write_Error("\n=========Opening Error Output File=========\r\n(%s) on %s\n",filename,timestring);

// now the file is created, re-open with append mode

if (!fp_override)
{
fclose(fp_error);
if ((fp_error = fopen(filename,"a+"))==NULL)
   return(0);
}

// return success
return(1);

} // end Open_Error_File

///////////////////////////////////////////////////////////

int Close_Error_File(void)
{
// this function closes the error file

if (fp_error)
    {
    // write close file string
    Write_Error("\n=========Closing Error Output File=========");

    if (fp_error!=stdout || fp_error!=stderr)
    {
    // close the file handle
    fclose(fp_error);
    } 
    
    fp_error = NULL;

    // return success
    return(1);
    } // end if
else
   return(0);

} // end Close_Error_File

///////////////////////////////////////////////////////////


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值