输入与输出不是C语言中的一部分,然而,程序与环境的交互具有非常重要的意义。《The C programming language》中第7章,描述了标准库——一系列提供输入与输出、字符串操作、存储管理、数学函数等函数及其它由C提供的服务。
这类函数定义在一系列头文件中,包括<stdio.h>、<string.h>和<ctype.h>,这些,读者可以在需要时自己进入相应头文件说明中去看,在《The C programming language》的Appendix B(附录B)中已言简意赅地有所说明。
这里,我主要记下关于C语言中变长型函数参数的笔记。
这里主要关于printf的一个微小版本来显示如何写一个可移植的程序,这个程序处理变长的函数参数。
正确的printf声明是如下:
int printf(char *fmt,...)
这里,声明中...意味着这里的参数数量和类型是变化的,是不确定的。声明...只能在参数列表的尾部出现。《The C programming language》中相应部分是这样解释的,
The standard header<strarg.h> contains a set of macro definitions that define how to step through(遍历)an argument list.The implementation of this header will vary from machine to machine ,but the interface it presents is uniform.
The type va_list is used to declare a variable that will refer to each argument in turn.在下面的程序中,即变量ap,for "argument pointer".The macro va_start initializes ap to point to the first unamed argument.It must be called once before ap is used.There must be at least one named argument;the final named argument is used by va_start to get started.
Each call of va_arg returns one argument and steps ap to the next; va_arg uses a type name to determine what type to return and how big a step to take. Finally, va_end does whatever cleanup is necessary. It must be called before the program returns.
那么,示例程序如下:
/*minprintf:minimal printf with variable argument list*/
#include<stdarg.h>/*for va_list and va_start() 銆乿a_end() marcro*/
#include<stdio.h>
/*minprintf:minimal printf with variable argument list*/
void minprintf(char *fmt,...)
{
va_list ap;/*points to each unnamed arg in turn*/
char *p,*sval;
int ival;
double dval;
va_start(ap,fmt);/*make ap point to 1st unnamed arg*/
for(p=fmt;*p;p++){
if(*p!='%'){
putchar(*p);
continue;
}
switch(*++p){
case 'd':
ival=va_arg(ap,int);
printf("%d",ival);
break;
case 'f':
dval=va_arg(ap,double);
printf("%f",dval);
break;
case 's':
for(sval=va_arg(ap,char *);*sval;sval++)
putchar(*sval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap);/*clean up when done*/
}
int main(void)
{
int d=1;
double f=3.14125926;
minprintf("%d\n",d);
minprintf("%f\n",f);
minprintf("%d %f\n",d,f);
}
运行结果为:
1
3.141259
1 3.141259