2009年2月12日星期四

trick in scanf

libjingle has a very tricky use of scanf and printf in httpcommon.cc

"%.*s" used in printf and "%*s%n %n%*s%n" used in scanf.

no offical explainations found so far.But you can figure out what they mean if you run the following exmaple code.

#include

int main()
{
  char path[] = "/test.html";
  printf("%s %.*s HTTP/%s\n", "Get", sizeof(path),path, "1.1");
 
  char line[256];
  sprintf(line,"%s %.*s HTTP/%s", "Get", sizeof(path),path, "1.1");
 
  int vmajor, vminor;
  int vend, dstart, dend;
  int ret = sscanf(line, "%*s%n %n%*s%n HTTP/%lu.%lu", &vend, &dstart, &dend, &vmajor, &vminor);
  
  printf("result: %d ",ret);
  printf("vend = %d ", vend);
  printf("dstart = %d ", dstart);
  printf("dend = %d ", dend);
  printf("vmajor = %d ", vmajor);
  printf("vminor = %d ", vminor);
  
 system("pause");
}


Results :

Get /test.html HTTP/1.1
result: 2 vend = 3 dstart = 4 dend = 14 vmajor = 1 vminor = 1 请按任意键继续. .

没有评论:

发表评论