C language function
printf has a very different parameter which is
..., something like this below:
int printf(const char *format, ...);
It's something about var_list dealing with var_args. I have a similar function for recording log informations.
void LOG(const char* format,...) {
va_list list;
time_t t=time(NULL);
tm* tp=localtime(&t);
char log_spin[256]="";
char log_buffer[1024*4]="";
if(format==NULL||!LOGFILE) return;
sprintf(log_spin,"[%04d-%02d-%02d %02d:%02d:%02d]",
tp->tm_year+1900,tp->tm_mon+1,tp->tm_mday,
tp->tm_hour,tp->tm_min,tp->tm_sec);
strcpy(log_buffer,log_spin);
size_t occuppied=strlen(log_buffer);
size_t remain=sizeof(log_buffer)-occuppied;
int count=0;
va_start(list,format);
count=vsnprintf(&log_buffer[strlen(log_buffer)],remain,format,list);
va_end(list);
if(count>=remain) sprintf(&log_buffer[sizeof(log_buffer)-5],"...\n\0");
else log_buffer[strlen(log_buffer)]='\n';
fprintf(LOGFILE,log_buffer);
fflush(LOGFILE);
}
This codes use the simiar function
vsnprintf dealing with format and recording parameters. It worked well utill recording parameters contains some characters like %, which when I tried to log some url with muti-bytes characters, as you know not supported in URL, there would be some conversion by using % together with hex value like %2d%4f...
My URL may like this:
https://www.zhihu.com/search?hybrid_search_extra=%7B%22sourceType%22%3A%22answer%22%2C%22sourceId%22%3A1228623761%7D&hybrid_search_source=Entity&q=%E6%9D%8E%E7%8E%89%E6%B9%96&search_source=Entity&type=content
see, there is a lot characters including %.
But, when you pass the url to this LOG function , sh*t happened. When I try to debug it, exception occurried (MSVC). OK, I believe there is something wrong with my LOG codes. Did the standard C function "printf" support it? I try to print the same url on console, all OK! That means there is a proper way to deal with % character which I just don't know. There must be a standard answer for it.
So, This is my problem , how to deal with character % in va_list?
What I have tried:
To simplify my code , I paste the code and the test input here.
int vsnprintf_test(char* format,...) {
char buffer[256]={0};
va_list list;
int count=0;
va_start(list,format);
count=vsnprintf(buffer,sizeof(buffer),format,list);
va_end(list);
printf(buffer);
return count;
}
the caller:
char msg[256] = { 0 };msg[0] = '%'; msg[1] = 'A';
printf("%s\n",msg); vsnprintf_test(msg);
I don't know how to fix this code. How did function printf do with character %?