在日志文件中很多情况并不指定输入参数的数量,因此常常被设计成可变长度的函数。通常会使用...
以下是我根据自己工作需求改变的日志文件的代码:
#include <stdarg.h>
#include <stdio.h>
#include <time.h>
// 类似printf("%s, %d", "nihao ",1); //这种类型
int set_log_info(const char* pformat, ...) {
time_h t;
struct tm* timeStruct;
va_list pvar;
int nlen;
char log_info[1024];
char filename[1024];
memset(log_info,0,sizeof(log_info));
memset(filename,0,sizeof(filename));
fputs("you/log/file/path/log.txt",filename);
// get time info
time(&t);
timeStruct = localtime(&t);
nlen = sprintf(loginfo, "%04d.%02d.%02d-%02d:%02d:%02d \t ", \
timeStruct->tm_year + 1900 \
timeStruct->tm_mon + 1 \
timeStruct->tm_mday \
timeStruct->tm_hour \
timeStruct->tm_min \
timeStruct->tm_sec);
va_start(pvar,pformat);
nlen += vsprintf(log_info + nlen, pformat, pvar);
va_end(pvar);
nlen += sprintf(log_info + nlen,"\n");
if( (fp = fopen(filename, "a+")) == NULL) {
printf("Log file open failed! \n");
return -1;
}
fprintf(fp,log_info);
close(fp);
return 0;
}
在const char* 变量之前还是能加一些其他参数的。va_list这些东西都在stdarg.h这个头文件中,因此需要引入这个头文件
除此之外,我在runoob上看到了关于...另外一种用法。在...之前指明输入参数的数量,具体代码如下:
#include <stdio.h>
#include <stdarg.h>
int flexibleParam(int num,...){
va_list pvar;
int i;
va_start(pvar,num);
for(i = 0 ; i < num ; i ++){
printf("%d\n", va_arg(pvar,int));
}
}
在runoob分享的笔记中有人指出这类似一种压栈的过程(次序为从右往左压,出则从左往有出)。
事实上我做实验发现,这些数据是竟跟在传入个数的地址后面的(即&num),实验代码如下:
#include <stdio.h>
int flexibleParam(int num, ...){
int* pnum = #
int i;
for(i = 0 ; i < num + 1; i ++){
printf("%d\n", *(pnum + i));
}
return 0;
}
做了这么多之后可能肯定会思考,如果我们传入的并不是int类型怎么办呢?
实验没做完,之后再补吧
该随笔纯属自己工作上遇到的东西进行整理,与本人工作内容无关。如果有什么问题还希望各位指正。