您的位置:首页 > 编程语言 > C语言/C++

用C语言开发一个BT下载软件 (四) ------ 代码实现-3-出错处理模块和运行日志模块

2017-12-30 12:14 911 查看
出错处理模块

      出错处理模块,主要定义了一些错误类型,以及发生导致程序终止的致命性错误时程序的响应。

//bterror.h

#ifndef BTERROR_H
#define BTERROR_H

#define FILE_FD_ERR -1 // 无效的文件描述符
#define FILE_READ_ERR -2 // 读文件失败
#define FILE_WRITE_ERR -3 // 写文件失败
#define INVALID_METAFILE_ERR -4 // 无效的种子文件
#define INVALID_SOCKET_ERR -5 // 无效的套接字
#define INVALID_TRACKER_URL_ERR -6 // 无效的Tracker URL
#define INVALID_TRACKER_REPLY_ERR -7 // 无效的Tracker回应
#define INVALID_HASH_ERR -8 // 无效的hash值
#define INVALID_MESSAGE_ERR -9 // 无效的消息
#define INVALID_PARAMETER_ERR -10 // 无效的函数参数
#define FAILED_ALLOCATE_MEM_ERR -11 // 申请动态内存失败
#define NO_BUFFER_ERR -12 // 没有足够的缓冲区
#define READ_SOCKET_ERR -13 // 读套接字失败
#define WRITE_SOCKET_ERR -14 // 写套接字失败
#define RECEIVE_EXIT_SIGNAL_ERR -15 // 接收到退出程序的信号

// 用于提示致命性的错误,程序将终止
void btexit(int errno,char *file,int line);

#endif
//bterror.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "bterror.h"

void btexit(int errno,char *file,int line)
{
printf("exit at %s : %d with error number : %d\n",file, line, errno);
exit(errno);
}

运行日志模块
      本模块负责记录程序运行的日志,以备查询和分析程序行为,由log.h和log.c两个文件构成。

//log.h

#ifndef LOG_H
#define LOG_H
#include <stdarg.h>

// 用于记录程序的行为
void logcmd(char *fmt,...);

// 打开日志文件
int init_logfile(char *filename);

// 将程序运行日志记录到文件
int logfile(char *file,int line,char *msg);

#endif
//log.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include "log.h"

//日志文件的描述符
int logfile_fd = -1;

//在命令行上打印一条日志
void logcmd(char *fmt,...)
{
va_list ap;

va_start(ap,fmt);
vprintf(fmt,ap);
va_end(ap);
}

//打开记录日志的文件
int init_logfile(char *filename)
{
logfile_fd = open(filename,O_RDWR|O_CREAT|O_APPEND,0666);
if(logfile_fd < 0) {
printf("open logfile failed\n");
return -1;
}

return 0;
}

//将一条日志写入日志文件
int logfile(char *file,int line,char *msg)
{
char buff[256];

if(logfile_fd < 0)
return -1;

snprintf(buff,256,"%s:%d %s\n",file,line,msg);
write(logfile_fd,buff,strlen(buff));

return 0;
}


      函数logcmd是一个变长参数的函数,也就是函数的参数个数是可变的,类似于printf函数。语句"logcmd("%s:%d error\n",__FILE__,__LINE__);"的功能与"printf("%s:%d error\n",__FILE__,__LINE__)"功能相同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐