第一章: C语言概论 C语言的发展过程   C语言是在70年代初问世的。一九七八年由美国电话电报公司(AT&T)贝尔实验室正式发表了C语言。同时由B.W.Kernighan和D.M.Ritchit合著了著名的“THE C PROGRAMMING LANGUAGE”一书。通常简称为《K&R》,也有人称之为《K&R》标准。但是,在《K&R》中并没有定义一个完整的标准C语言,后来由美国国家标准学会在此基础上制定了一个C 语言标准,于一九八三年发表。通常称之为ANSI C。 当代最优秀的程序设计语言   早期的C语言主要是用于UNIX系统。由于C语言的强大功能和各方面的优点逐渐为人们认识,到了八十年代,C开始进入其它操作系统,并很快在各类大、中、小和微型计算机上得到了广泛的使用。成为当代最优秀的程序设计语言之一。 C语言的特点   C语言是一种结构化语言。它层次清晰,便于按模块化方式组织程序,易于调试和维护。C语言的表现能力和处理能力极强。它不仅具有丰富的运算符和数据类型,便于实现各类复杂的数据结构。它还可以直接访问内存的物理地址,进行位(bit)一级的操作。由于C语言实现了对硬件的编程操作,因此C语言集高级语言和低级语言的功能于一体。既可用于系统软件的开发,也适合于应用软件的开发。此外,C语言还具有效率高,可移植性强等特点。因此广泛地移植到了各类各型计算机上,从而形成了多种版本的C语言。 C语言版本   目前最流行的C语言有以下几种:    ·Microsoft C 或称 MS C    ·Borland Turbo C 或称 Turbo C    ·AT&T C   这些C语言版本不仅实现了ANSI C标准,而且在此基础上各自作了一些扩充,使之更加方便、完美。 面向对象的程序设计语言   在C的基础上,一九八三年又由贝尔实验室的Bjarne Strou-strup推出了C++。 C++进一步扩充和完善了C语言,成为一种面向 对象的程序设计语言。C++目前流行的最新版本是Borland C++4.5,Symantec C++6.1,和Microsoft VisualC++ 2.0。C++提出了一些更为深入的概念,它所支持的这些面向对象的概念容易将问题空间直接地映射到程序空间,为程序员提供了一种与传统结构程序设计不同的思维方式和编程方法。因而也增加了整个语言的复杂性,掌握起来有一定难度。 C和C++   但是,C是C++的基础,C++语言和C语言在很多方面是兼容的。因此,掌握了C语言,再进一步学习C++就能以一种熟悉的语法来学习面向对象的语言,从而达到事半功倍的目的。 C源程序的结构特点   为了说明C语言源程序结构的特点,先看以下几个程序。这几个程 序由简到难,表现了C语言源程序在组成结构上的特点。虽然有关内容还未介绍,但可从这些例子中了解到组成一个C源程序的基本部分和书写格式。main() { printf("c语言世界www.vcok.com,您好!\n"); }   main是主函数的函数名,表示这是一个主函数。每一个C源程序都必须有,且只能有一个主函数(main函数)。函数调用语句,printf函数的功能是把要输出的内容送到显示器去显示。printf函数是一个由系统定义的标准函数,可在程序中直接调用。 #include #include main() { double x,s; printf("input number:\n"); scanf("%lf",&x); s=sin(x); printf("sine of %lf is %lf\n",x,s); } 每行注释 include称为文件包含命令扩展名为.h的文件也称为头文件或首部文件 定义两个实数变量,以被后面程序使用 显示提示信息 从键盘获得一个实数x 求x的正弦,并把它赋给变量s 显示程序运算结果 main函数结束      程序的功能是从键盘输入一个数x,求x的正弦值,然后输出结果。在main()之前的两行称为预处理命令(详见后面)。预处理命令还有其它几种,这里的include 称为文件包含命令,其意义是把尖括号""或引号<>内指定的文件包含到本程序来,成为本程序的一部分。被包含的文件通常是由系统提供的,其扩展名为.h。因此也称为头文件或首部文件。C语言的头文件中包括了各个标准库函数的函数原型。因此,凡是在程序中调用一个库函数时,都必须包含该函数原型所在的头文件。在本例中,使用了三个库函数:输入函数scanf,正弦函数sin,输出函数printf。sin函数是数学函数,其头文件为math.h文件,因此在程序的主函数前用include命令包含了math.h。scanf和printf是标准输入输出函数,其头文件为stdio.h,在主函数前也用include命令包含了stdio.h文件。   需要说明的是,C语言规定对scanf和printf这两个函数可以省去对其头文件的包含命令。所以在本例中也可以删去第二行的包含命令#include。同样,在例1.1中使用了printf函数,也省略了包含命令。   在例题中的主函数体中又分为两部分,一部分为说明部分,另一部分执行部分。说明是指变量的类型说明。例题中未使用任何变量,因此无说明部分。C语言规定,源程序中所有用到的变量都必须先说明,后使用,否则将会出错。这一点是编译型高级程序设计语言的一个特点,与解释型的BASIC语言是不同的。说明部分是C源程序结构中很重要的组成部分。本例中使用了两个变量x,s,用来表示输入的自变量和sin函数值。由于sin函数要求这两个量必须是双精度浮点型,故用类型说明符double来说明这两个变量。说明部分后的四行为执行部分或称为执行语句部分,用以完成程序的功能。执行部分的第一行是输出语句,调用printf函数在显示器上输出提示字符串,请操作人员输入自变量x的值。第二行为输入语句,调用scanf函数,接受键盘上输入的数并存入变量x中。第三行是调用sin函数并把函数值送到变量s中。第四行是用printf 函数输出变量s的值,即x的正弦值。程序结束。 printf("input number:\n"); scanf("%lf",'C10F10&x); s=sin(x); printf("sine of %lf is %lf\n",'C10F10x,s);   运行本程序时,首先在显示器屏幕上给出提示串input number,这是由执行部分的第一行完成的。用户在提示下从键盘上键入某一数,如5,按下回车键,接着在屏幕上给出计算结果。 输入和输出函数   在前两个例子中用到了输入和输出函数scanf和 printf,在第三章中我们要详细介绍。这里我们先简单介绍一下它们的格式,以便下面使用。scanf和 printf这两个函数分别称为格式输入函数和格式输出函数。其意义是按指定的格式输入输出值。因此,这两个函数在括号中的参数表都由以下两部分组成: “格式控制串”,参数表  格式控制串是一个字符串,必须用双引号括起来,它表示了输入输出量的数据类型。各种类型的格式表示法可参阅第三章。在printf函数中还可以在格式控制串内出现非格式控制字符,这时在显示屏幕上将原文照印。参数表中给出了输入或输出的量。当有多个量时,用逗号间隔。例如: printf("sine of %lf is %lf\n",x,s);   其中%lf为格式字符,表示按双精度浮点数处理。它在格式串中两次现,对应了x和s两个变量。其余字符为非格式字符则照原样输出在屏幕上 int max(int a,int b); main(){ int x,y,z; printf("input two numbers:\n");scanf("%d%d",&x,&y); z=max(x,y); printf("maxmum=%d",z); } int max(int a,int b){ if(a>b)return a;else return b; } 此函数的功能是输入两个整数,输出其中的大数。 /*函数说明*/ /*主函数*/ /*变量说明*/ /*输入x,y值*/ /*调用max函数*/ /*输出*/ /*定义max函数*/ /*把结果返回主调函数*/   上面例中程序的功能是由用户输入两个整数,程序执行后输出其中较大的数。本程序由两个函数组成,主函数和max 函数。函数之间是并列关系。可从主函数中调用其它函数。max 函数的功能是比较两个数,然后把较大的数返回给主函数。max 函数是一个用户自定义函数。因此在主函数中要给出说明(程序第三行)。可见,在程序的说明部分中,不仅可以有变量说明,还可以有函数说明。关于函数的详细内容将在第五章介绍。在程序的每行后用/*和*/括起来的内容为注释部分,程序不执行注释部分。   上例中程序的执行过程是,首先在屏幕上显示提示串,请用户输入两个数,回车后由scanf函数语句接收这两个数送入变量x,y中,然后调用max函数,并把x,y 的值传送给max函数的参数a,b。在max函数中比较a,b的大小,把大者返回给主函数的变量z,最后在屏幕上输出z的值。 C源程序的结构特点 1.一个C语言源程序可以由一个或多个源文件组成。 2.每个源文件可由一个或多个函数组成。 3.一个源程序不论由多少个文件组成,都有一个且只能有一个main函数,即主函数。 4.源程序中可以有预处理命令(include 命令仅为其中的一种),预处理命令通常应放在源文件或源程序的最前面。 5.每一个说明,每一个语句都必须以分号结尾。但预处理命令,函数头和花括号“}”之后不能加分号。 6.标识符,关键字之间必须至少加一个空格以示间隔。若已有明显的间隔符,也可不再加空格来间隔。 书写程序时应遵循的规则   从书写清晰,便于阅读,理解,维护的角度出发,在书写程序时 应遵循以下规则: 1.一个说明或一个语句占一行。 2.用{} 括起来的部分,通常表示了程序的某一层次结构。{}一般与该结构语句的第一个字母对齐,并单独占一行。 3.低一层次的语句或说明可比高一层次的语句或说明缩进若干格后书写。以便看起来更加清晰,增加程序的可读性。在编程时应力求遵循这些规则,以养成良好的编程风格。 C语言的字符集   字符是组成语言的最基本的元素。C语言字符集由字母,数字,空格,标点和特殊字符组成。在字符常量,字符串常量和注释中还可以使用汉字或其它可表示的图形符号。 1.字母  小写字母a~z共26个,大写字母A~Z共26个 2.数字  0~9共10个 3.空白符 空格符、制表符、换行符等统称为空白符。空白符只在字符常量和字符串常量中起作用。在其它地方出现时,只起间隔作用, 编译程序对它们忽略。因此在程序中使用空白符与否,对程序的编译不发生影响,但在程序中适当的地方使用空白符将增加程序的清晰性和可读性。 4.标点和特殊字符 C语言词汇   在C语言中使用的词汇分为六类:标识符,关键字,运算符,分隔符,常量,注释符等。 1.标识符   在程序中使用的变量名、函数名、标号等统称为标识符。除库函数的函数名由系统定义外,其余都由用户自定义。C 规定,标识符只能是字母(A~Z,a~z)、数字(0~9)、下划线()组成的字符串,并且其第一个字符必须是字母或下划线。 以下标识符是合法的: a,x, 3x,BOOK 1,sum5 以下标识符是非法的: 3s 以数字开头 s*T 出现非法字符* -3x 以减号开头 bowy-1 出现非法字符-(减号)   在使用标识符时还必须注意以下几点: (1)标准C不限制标识符的长度,但它受各种版本的C 语言编译系统限制,同时也受到具体机器的限制。例如在某版本C 中规定标识符前八位有效,当两个标识符前八位相同时,则被认为是同一个标识符。 (2)在标识符中,大小写是有区别的。例如BOOK和book 是两个不同的标识符。 (3)标识符虽然可由程序员随意定义,但标识符是用于标识某个量的符号。因此,命名应尽量有相应的意义,以便阅读理解,作到“顾名思义”。 2.关键字   关键字是由C语言规定的具有特定意义的字符串,通常也称为保留字。用户定义的标识符不应与关键字相同。C语言的关键字分为以下几类: (1)类型说明符 用于定义、说明变量、函数或其它数据结构的类型。如前面例题中用到的int,double等 (2)语句定义符 用于表示一个语句的功能。如例1.3中用到的if else就是条件语句的语句定义符。 (3)预处理命令字 用于表示一个预处理命令。如前面各例中用到的include。 3.运算符   C语言中含有相当丰富的运算符。运算符与变量,函数一起组成表达式,表示各种运算功能。运算符由一个或多个字符组成。 4.分隔符   在C语言中采用的分隔符有逗号和空格两种。逗号主要用在类型说明和函数参数表中,分隔各个变量。空格多用于语句各单词之间,作间隔符。在关键字,标识符之间必须要有一个以上的空格符作间隔, 否则将会出现语法错误,例如把int a;写成 inta;C编译器会把inta当成一个标识符处理,其结果必然出错。 5.常量   C 语言中使用的常量可分为数字常量、字符常量、字符串常量、符号常量、转义字符等多种。在第二章中将专门给予介绍。 6.注释符   C 语言的注释符是以“/*”开头并以“*/”结尾的串。在“/*”和“*/”之间的即为注释。程序编译时,不对注释作任何处理。注释可出现在程序中的任何位置。注释用来向用户提示或解释程序的意义。在调试程序中对暂不使用的语句也可用注释符括起来,使翻译跳过不作处理,待调试结束后再去掉注释符。 第二章: 数据类型、运算符、表达式 C语言的数据类型   在第一课中,我们已经看到程序中使用的各种变量都应预先加以说明,即先说明,后使用。对变量的说明可以包括三个方面: ·数据类型 ·存储类型 ·作用域   在本课中,我们只介绍数据类型说明。其它说明在以后各章中陆续介绍。所谓数据类型是按被说明量的性质,表示形式,占据存储空间的多少,构造特点来划分的。在C语言中,数据类型可分为:基本数据类型,构造数据类型,指针类型,空类型四大类。 1.基本数据类型   基本数据类型最主要的特点是,其值不可以再分解为其它类型。也就是说,基本数据类型是自我说明的。 2.构造数据类型构造数据类型   是根据已定义的一个或多个数据类型用构造的方法来定义的。也就是说,一个构造类型的值可以分解成若干个“成员”或“元素”。每个“成员”都是一个基本数据类型或又是一个构造类型。在C语言中,构造类型有以下几种: ·数组类型 ·结构类型 ·联合类型 3.指针类型   指针是一种特殊的,同时又是具有重要作用的数据类型。其值用来表示某个量在内存储器中的地址。虽然指针变量的取值类似于整型量,但这是两个类型完全不同的量,因此不能混为一谈。4.空类型在调用函数值时,通常应向调用者返回一个函数值。这个返回的函数值是具有一定的数据类型的,应在函数定义及函数说明中给以说明,例如在例题中给出的max函数定义中,函数头为: int max(int a,int b);其中“int ”类型说明符即表示该函数的返回值为整型量。又如在例题中,使用了库函数 sin,由于系统规定其函数返回值为双精度浮点型,因此在赋值语句s=sin (x);中,s 也必须是双精度浮点型,以便与sin函数的返回值一致。所以在说明部分,把s说明为双精度浮点型。但是,也有一类函数,调用后并不需要向调用者返回函数值, 这种函数可以定义为“空类型”。其类型说明符为void。在第五章函数中还要详细介绍。在本章中,我们先介绍基本数据类型中的整型、浮点型和字符型。其余类型在以后各章中陆续介绍。   对于基本数据类型量,按其取值是否可改变又分为常量和变量两种。在程序执行过程中,其值不发生改变的量称为常量,取值可变的量称为变量。它们可与数据类型结合起来分类。例如,可分为整型常量、整型变量、浮点常量、浮点变量、字符常量、字符变量、枚举常量、枚举变量。在程序中,常量是可以不经说明而直接引用的,而变量则必须先说明后使用。 整型量 整型量包括整型常量、整型变量。整型常量就是整常数。在C语言中,使用的整常数有八进制、十六进制和十进制三种。 整型常量 1.八进制整常数八进制整常数必须以0开头,即以0作为八进制数的前缀。数码取值为0~7。八进制数通常是无符号数。 以下各数是合法的八进制数: 015(十进制为13) 0101(十进制为65) 0177777(十进制为65535) 以下各数不是合法的八进制数: 256(无前缀0) 03A2(包含了非八进制数码) -0127(出现了负号) 2.十六进制整常数 十六进制整常数的前缀为0X或0x。其数码取值为0~9,A~F或a~f。 以下各数是合法的十六进制整常数: 0X2A(十进制为42)  0XA0 (十进制为160)  0XFFFF (十进制为65535) 以下各数不是合法的十六进制整常数: 5A (无前缀0X)  0X3H (含有非十六进制数码) 3.十进制整常数 十进制整常数没有前缀。其数码为0~9。 以下各数是合法的十进制整常数: 237 -568 65535 1627 以下各数不是合法的十进制整常数: 023 (不能有前导0) 23D (含有非十进制数码)   在程序中是根据前缀来区分各种进制数的。因此在书写常数时不要把前缀弄错造成结果不正确。4.整型常数的后缀在16位字长的机器上,基本整型的长度也为16位,因此表示的数的范围也是有限定的。十进制无符号整常数的范围为0~65535,有符号数为-32768~+32767。八进制无符号数的表示范围为0~0177777。十六进制无符号数的表示范围为0X0~0XFFFF或0x0~0xFFFF。如果使用的数超过了上述范围,就必须用长整型数来表示。长整型数是用后缀“L”或“l”来表示的。例如: 十进制长整常数 158L (十进制为158) 358000L (十进制为-358000) 八进制长整常数 012L (十进制为10) 077L (十进制为63) 0200000L (十进制为65536) 十六进制长整常数 0X15L (十进制为21) 0XA5L (十进制为165) 0X10000L (十进制为65536)      长整数158L和基本整常数158 在数值上并无区别。但对158L,因为是长整型量,C编译系统将为它分配4个字节存储空间。而对158,因为是基本整型,只分配2 个字节的存储空间。因此在运算和输出格式上要予以注意,避免出错。无符号数也可用后缀表示,整型常数的无符号数的后缀为“U”或“u”。例如: 358u,0x38Au,235Lu 均为无符号数。前缀,后缀可同时使用以表示各种类型的数。如0XA5Lu表示十六进制无符号长整数A5,其十进制为165。 整型变量 整型变量可分为以下几类: 1.基本型 类型说明符为int,在内存中占2个字节,其取值为基本整常数。 2.短整量 类型说明符为short int或short'C110F1。所占字节和取值范围均与基本型相同。 3.长整型 类型说明符为long int或long ,在内存中占4个字节,其取值为长整常数。 4.无符号型 类型说明符为unsigned。 无符号型又可与上述三种类型匹配而构成: (1)无符号基本型 类型说明符为unsigned int或unsigned。 (2)无符号短整型 类型说明符为unsigned short (3)无符号长整型 类型说明符为unsigned long 各种无符号类型量所占的内存空间字节数与相应的有符号类型量相同。但由于省去了符号位,故不能表示负数。 下表列出了Turbo C中各类整型量所分配的内存字节数及数的表示范围。 类型说明符    数的范围     分配字节数 int       -32768~32767     ■■ short int    -32768~32767     ■■ signed int    -32768~32767     ■■ unsigned int   0~65535        ■■ long int  -2147483648~2147483647  ■■■■ unsigned long  0~4294967295     ■■■■ 整型变量的说明 变量说明的一般形式为: 类型说明符 变量名标识符,变量名标识符,...; 例如: int a,b,c; (a,b,c为整型变量) long x,y; (x,y为长整型变量) unsigned p,q; (p,q为无符号整型变量) 在书写变量说明时,应注意以下几点: 1.允许在一个类型说明符后,说明多个相同类型的变量。各变量名之间用逗号间隔。类型说明符与变量名之间至少用一个空格间隔。 2.最后一个变量名之后必须以“;”号结尾。 3.变量说明必须放在变量使用之前。一般放在函数体的开头部分。 [Practice] //1int a,b; short int c; short d=100; a=d-20; b=a+d; c=a+b+d; d=d-a+c-b;'Vtable a,2,0 b,2,0 c,2,0 d,2,100 of Vtable 'Vupdate 1,0;2,0 3,0 4,100 1,80 2,180 3,360 4,200 of Vupdate of Practice [Practice] //2int a=5; int b=9; long int c; long d; c=a+b-7; d=a*b*c; c=d*d*d; a=c-d;'Vtable a,2,5 b,2,9 c,4,0 d,4,0 of Vtable 'Vupdate 1,5 2,9 3,0 4,0 3,7 4,315 3,31255875 1,-5112 of Vupdate of Practice [Practice] //3int a=6,b=19; unsigned int c; int d; c=a-b+7; d=b*c; a=b+c+d; b=-a;'Vtable a,2,6 b,2,19 c,2,0 d,2,0 of Vtable 'Vupdate 1,6;2,19 3,0 4,0 3,65530 4,-114 1,-101 2,101 of Vupdate of Practice void main(){ long x,y; int a,b,c,d; x=5; y=6; a=7; b=8; c=x+a; d=y+b; printf("c=x+a=%d,d=y+b=%d\n",c,d); } 将main说明为返回void,即不返回任何类型的值 x,y被定义为long型 a,b,c,d被定义为int型 5->x 6->y 7->a 8->b x+a->c y+b->d 显示程序运行结果 of long x,y; int a,b,c,d; c=x+a; d=y+b;   从程序中可以看到:x, y是长整型变量,a, b是基本整型变量。它们之间允许进行运算,运算结果为长整型。但c,d被定义为基本整型,因此最后结果为基本整型。本例说明,不同类型的量可以参与运算并相互赋值。其中的类型转换是由编译系统自动完成的。有关类型转换的规则将在以后介绍。 实型量 实型常量 实型也称为浮点型。实型常量也称为实数或者浮点数。在C语言中,实数只采用十进制。它有二种形式: 十进制数形式指数形式 1.十进制数形式 由数码0~ 9和小数点组成。例如:0.0,.25,5.789,0.13,5.0,300.,-267.8230等均为合法的实数。 2.指数形式 由十进制数,加阶码标志“e”或“E”以及阶码(只能为整数,可以带符号)组成。其一般形式为a E n (a为十进制数,n为十进制整数)其值为 a*10,n 如: 2.1E5 (等于2.1*10,5), 3.7E-2 (等于3.7*10,)-2*) 0.5E7 (等于0.5*10,7), -2.8E-2 (等于-2.8*10,)-2*)以下不是合法的实数 345 (无小数点) E7 (阶码标志E之前无数字)  -5 (无阶码标志) 53.-E3 (负号位置不对) 2.7E (无阶码) 标准C允许浮点数使用后缀。后缀为“f”或“F”即表示该数为浮点数。如356f和356.是等价的。例2.2说明了这种情况: void main() { printf("%f\n%f\n",356.,356f); } void 指明main不返回任何值 利用printf显示结果 结束 实型变量 实型变量分为两类:单精度型和双精度型, 其类型说明符为float 单精度说明符,double 双精度说明符。在Turbo C中单精度型占4个字节(32位)内存空间,其数值范围为3.4E-38~3.4E+38,只能提供七位有效数字。双精度型占8 个字节(64位)内存空间,其数值范围为1.7E-308~1.7E+308,可提供16位有效数字。 实型变量说明的格式和书写规则与整型相同。 例如: float x,y; (x,y为单精度实型量)     double a,b,c; (a,b,c为双精度实型量) 实型常数不分单、双精度,都按双精度double型处理。 void main(){ float a; double b; a=33333.33333; b=33333.33333333333333; printf("%f\n%f\n",a,b); } 此程序说明float、double的不同 a ■■■■ b ■■■■■■■■ a<---33333.33333 b<---33333.33333333333;; 显示程序结果 此程序说明float、double的不同 float a; double b; a=33333.33333; b=33333.33333333333333; 从本例可以看出,由于a 是单精度浮点型,有效位数只有七位。而整数已占五位,故小数二位后之后均为无效数字。b 是双精度型,有效位为十六位。但Turbo C 规定小数后最多保留六位,其余部分四舍五入。 [Practice] //floatint a=32; float b; double d; b=12345678; d=b*100; d=d+a; d=d+58.123456;'Vtable a,2,32 b,4,0.0 d,8,0.0 of Vtable 'Vupdate 1,32 2,0 3,0 2,12345678.00000 3,1234567800 3,1234567832 3,1234567890.123456 of Vupdate of Practice [Practice] //1int a=543; float b; b=123.123962+a; b=b-100; a=b;'Vtable a,2,543 b,4,0.0 of Vtable 'Vupdate 1,543 2,0.0 2,123.123962 2,23.123962 1,23 of Vupdate of Practice 字符型量 字符型量包括字符常量和字符变量。 字符常量 字符常量是用单引号括起来的一个字符。例如'a','b','=','+','?'都是合法字符常量。在C语言中,字符常量有以下特点: 1.字符常量只能用单引号括起来,不能用双引号或其它括号。 2.字符常量只能是单个字符,不能是字符串。 3.字符可以是字符集中任意字符。但数字被定义为字符型之后就 不能参与数值运算。如'5'和5 是不同的。'5'是字符常量,不能参与运算。 转义字符 转义字符是一种特殊的字符常量。转义字符以反斜线"\"开头,后跟一个或几个字符。转义字符具有特定的含义,不同于字符原有的意义,故称“转义”字符。例如,在前面各例题printf函数的格式串中用到的“\n”就是一个转义字符,其意义是“回车换行”。转义字符主要用来表示那些用一般字符不便于表示的控制代码。 常用的转义字符及其含义 转义字符  转义字符的意义 \n      回车换行 \t      横向跳到下一制表位置 \v      竖向跳格 \b      退格 \r      回车 \f      走纸换页 \\      反斜线符"\" \'      单引号符 \a      鸣铃 \ddd     1~3位八进制数所代表的字符 \xhh     1~2位十六进制数所代表的字符 广义地讲,C语言字符集中的任何一个字符均可用转义字符来表示。表2.2中的\ddd和\xhh正是为此而提出的。ddd和hh分别为八进制和十六进制的ASCII代码。如\101表示字?quot;A" ,\102表示字母"B",\134表示反斜线,\XOA表示换行等。转义字符的使用 void main() { int a,b,c; a=5; b=6; c=7; printf("%d\n\t%d %d\n %d %d\t\b%d\n",a,b,c,a,b,c); } 此程序练习转义字符的使用 a、b、c为整数 5->a,6->b,7->c 调用printf显示程序运行结果 printf("%d\n\t%d %d\n %d %d\t\b%d\n",a,b,c,a,b,c); 程序在第一列输出a值5之后就是“\n”,故回车换行;接着又是“\t”,于是跳到下一制表位置(设制表位置间隔为8),再输出b值6;空二格再输出c 值7后又是"\n",因此再回车换行;再空二格之后又输出a值5;再空三格又输出b的值6;再次后"\t"跳到下一制表位置(与上一行的6 对齐),但下一转义字符“\b”又使退回一格,故紧挨着6再输出c值7。 字符变量 字符变量的取值是字符常量,即单个字符。字符变量的类型说明符是char。字符变量类型说明的格式和书写规则都与整型变量相同。 例如: char a,b; 每个字符变量被分配一个字节的内存空间,因此只能存放一个字符。字符值是以ASCII码的形式存放在变量的内存单元之中的。如x的 十进制ASCII码是120,y的十进制ASCII码是121。对字符变量a,b赋予'x'和'y'值: a='x';b='y';实际上是在a,b两个单元内存放120和121的二进制代码: a 0 1 1 1 1 0 0 0      b 0 1 1 1 1 0 0 1 所以也可以把它们看成是整型量。 C语言允许对整型变量赋以字符值,也允许对字符变量赋以整型值。在输出时, 允许把字符变量按整型量输出,也允许把整型量按字符量输出。 整型量为二字节量,字符量为单字节量,当整型量按字符型量处理时, 只有低八位字节参与处理。 main(){ char a,b; a=120; b=121; printf("%c,%c\n%d,%d\n",a,b,a,b); } a ■ b ■ a <-- 120 b <--- 121 显示程序结果 char a,b; a=120; b=121; 本程序中说明a,b为字符型,但在赋值语句中赋以整型值。从结果看,a,b值的输出形式取决于printf函数格式串中的格式符,当格式符为"c"时,对应输出的变量值为字符,当格式符为"d"时,对应输出的变量值为整数。 void main(){ char a,b; a='x'; b='y'; a=a-32; b=b-32; printf("%c,%c\n%d,%d\n",a,b,a,b); } a,b被说明为字符变量并赋予字符值 把小写字母换成大写字母 以整型和字符型输出 本例中,a,b被说明为字符变量并赋予字符值,C语言允许字符变量参与数值运算,即用字符的ASCII 码参与运算。由于大小写字母的ASCII 码相差32,因此运算后把小写字母换成大写字母。然后分别以整型和字符型输出。 [Practice] //charint a=49; char b; char d; b=a+10; d=a+b;'Vtable a,2,49 b,1,随机 d,1,随机 of Vtable 'Vupdate 1,49 2,随机 3,随机 2,';' 3,'l' of Vupdate of Practice [Practice] //char c1,c2; c1='a';c2='b'; c1=c1-32;c2=c2-32;'Vtable c1,1,随机 c2,1,随机 of Vtable 'Vupdate 1,随机;2,随机 1,'a';2,'b' 1,'A';2,'B' of Vupdate of Practice 字符串常量 字符串常量是由一对双引号括起的字符序列。例如: "CHINA" ,"C program: , "$12.5" 等都是合法的字符串常量。字符串常量和字符常量是不同的量。它们之间主要有以下区别: 1.字符常量由单引号括起来,字符串常量由双引号括起来。 2.字符常量只能是单个字符,字符串常量则可以含一个或多个字符。 3.可以把一个字符常量赋予一个字符变量,但不能把一个字符串常量赋予一个字符变量。在C语言中没有相应的字符串变量。 这是与BASIC 语言不同的。但是可以用一个字符数组来存放一个字符串常量。在数组一章内予以介绍。 4.字符常量占一个字节的内存空间。字符串常量占的内存字节数等于字符串中字节数加1。增加的一个字节中存放字符"\0"(ASCII码为0)。这是字符串结束的标志。例如,字符串 "C program"在内存中所占的字节为:C program\0。字符常量'a'和字符串常量"a"虽然都只有一个字符,但在内存中的情况是不同的。 'a'在内存中占一个字节,可表示为:a "a"在内存中占二个字节,可表示为:a\0符号常量 符号常量 在C语言中,可以用一个标识符来表示一个常量,称之为符号常量。符号常量在使用之前必须先定义,其一般形式为: #define 标识符 常量 其中#define也是一条预处理命令(预处理命令都?quot;#"开头),称为宏定义命令(在第九章预处理程序中将进一步介绍),其功能是把该标识符定义为其后的常量值。一经定义,以后在程序中所有出现该标识符的地方均代之以该常量值。习惯上符号常量的标识符用大写字母,变量标识符用小写字母,以示区别。 #define PI 3.14159 void main(){ float s,r; r=5; s=PI*r*r; printf("s=%f\n",s); } 由宏定义命令定义PI 为3.14159 s,r定义为实数 5->r PI*r*r->s 显示程序结果 float s,r; r=5; s=PI*r*r; 本程序在主函数之前由宏定义命令定义PI 为3.14159,在程序中即以该值代替PI 。s=PI*r*r等效于s=3.14159*r*r。应该注意的是,符号常量不是变量,它所代表的值在整个作用域内不能再改变。也就是说,在程序中,不能再用赋值语句对它重新赋值。 变量的初值和类型转换 变量赋初值 在程序中常常需要对变量赋初值,以便使用变量。语言程序中可有多种方法,在定义时赋以初值的方法,这种方法称为初始化。在变量说明中赋初值的一般形式为: 类型说明符 变量1= 值1,变量2= 值2,……; 例如: int a=b=c=5; float x=3.2,y=3f,z=0.75; char ch1='K',ch2='P'; 应注意,在说明中不允许连续赋值,如a=b=c=5是不合法的。 void main(){ int a=3,b,c=5; b=a+c; printf("a=%d,b=%d,c=%d\n",a,b,c); } a<---3,b<--0,c<---5 b<--a+c 显示程序运行结果 变量类型的转换 变量的数据类型是可以转换的。转换的方法有两种, 一种是自动转换,一种是强制转换。 自动转换 自动转换发生在不同数据类型的量混合运算时,由编译系统自动完成。自动转换遵循以下规则: 1.若参与运算量的类型不同,则先转换成同一类型,然后进行运算。 2.转换按数据长度增加的方向进行,以保证精度不降低。如int型和long型运算时,先把int量转成long型后再进行运算。 3.所有的浮点运算都是以双精度进行的,即使仅含float单精度量运算的表达式,也要先转换成double型,再作运算。 4.char型和short型参与运算时,必须先转换成int型。 5.在赋值运算中,赋值号两边量的数据类型不同时, 赋值号右边量的类型将转换为左边量的类型。 如果右边量的数据类型长度左边长时,将丢失一部分数据,这样会降低精度, 丢失的部分按四舍五入向前舍入。图21表示了类型自动转换的规则。 void main(){ float PI=3.14159; int s,r=5; s=r*r*PI; printf("s=%d\n",s); } PI<--3.14159 s<--0,r<--5 s<--r*r*PI 显示程序运行结果 float PI=3.14159; int s,r=5; s=r*r*PI; 本例程序中,PI为实型;s,r为整型。在执行s=r*r*PI语句时,r和PI都转换成double型计算,结果也为double型。但由于s为整型,故赋值结果仍为整型,舍去了小数部分。 强制类型转换 强制类型转换是通过类型转换运算来实现的。其一般形式为: (类型说明符) (表达式) 其功能是把表达式的运算结果强制转换成类型说明符所表示的类型。例如: (float) a 把a转换为实型(int)(x+y) 把x+y的结果转换为整型在使用强制转换时应注意以下问题: 1.类型说明符和表达式都必须加括号(单个变量可以不加括号),如把(int)(x+y)写成(int)x+y则成了把x转换成int型之后再与y相加了。 2.无论是强制转换或是自动转换,都只是为了本次运算的需要而对变量的数据长度进行的临时性转换,而不改变数据说明时对该变量定义的类型。 main(){ float f=5.75; printf("(int)f=%d,f=%f\n",(int)f,f); } f<--5.75 将float f强制转换成int f float f=5.75;printf("(int)f=%d,f=%f\n",(int)f,f); 本例表明,f虽强制转为int型,但只在运算中起作用, 是临时的,而f本身的类型并不改变。因此,(int)f的值为 5(删去了小数)而f的值仍为5.75。 基本运算符和表达式 运算符的种类、优先级和结合性 C语言中运算符和表达式数量之多, 在高级语言中是少见的。正是丰富的运算符和表达式使C语言功能十分完善。 这也是C语言的主要特点之一。 C语言的运算符不仅具有不同的优先级, 而且还有一个特点,就是它的结合性。在表达式中, 各运算量参与运算的先后顺序不仅要遵守运算符优先级别的规定,还要受运算符结合性的制约, 以便确定是自左向右进行运算还是自右向左进行运算。 这种结合性是其它高级语言的运算符所没有的,因此也增加了C语言的复杂性。 运算符的种类C语言的运算符可分为以下几类: 1.算术运算符 用于各类数值运算。包括加(+)、减(-)、乘(*)、除(/)、求余(或称模运算,%)、自增(++)、自减(--)共七种。 2.关系运算符 用于比较运算。包括大于(>)、小于(<)、等于(==)、 大于等于(>=)、小于等于(<=)和不等于(!=)六种。 3.逻辑运算符 用于逻辑运算。包括与(&&)、或(||)、非(!)三种。 4.位操作运算符 参与运算的量,按二进制位进行运算。包括位与(&)、位或(|)、位非(~)、位异或(^)、左移(<<)、右移(>>)六种。 5.赋值运算符 用于赋值运算,分为简单赋值(=)、复合算术赋值(+=,-=,*=,/=,%=)和复合位运算赋值(&=,|=,^=,>>=,<<=)三类共十一种。 6.条件运算符 这是一个三目运算符,用于条件求值(?:)。 7.逗号运算符 用于把若干表达式组合成一个表达式(,)。 8.指针运算符 用于取内容(*)和取地址(&)二种运算。 9.求字节数运算符 用于计算数据类型所占的字节数(sizeof)。 10.特殊运算符 有括号(),下标[],成员(→,.)等几种。 优先级和结合性 C语言中,运算符的运算优先级共分为15级。1级最高,15级最低。在表达式中,优先级较高的先于优先级较低的进行运算。 而在一个运算量两侧的运算符优先级相同时, 则按运算符的结合性所规定的结合方向处理。 C语言中各运算符的结合性分为两种,即左结合性(自左至右)和右结合性(自右至左)。例如算术运算符的结合性是自左至右,即先左后右。如有表达式x-y+z则y应先与“-”号结合, 执行x-y运算,然后再执行+z的运算。这种自左至右的结合方向就称为“左结合性”。而自右至左的结合方向称为“右结合性”。 最典型的右结合性运算符是赋值运算符。如x=y=z,由于“=”的右结合性,应先执行y=z再执行x=(y=z)运算。 C语言运算符中有不少为右结合性,应注意区别,以避免理解错误。 算术运算符和算术表达式基本的算术运算符 1.加法运算符“+”加法运算符为双目运算符,即应有两个量参与加法运算。如a+b,4+8等。具有右结合性。 2.减法运算符“-”减法运算符为双目运算符。但“-”也可作负值运算符,此时为单目运算,如-x,-5等具有左结合性。 3.乘法运算符“*”双目运算,具有左结合性。 4.除法运算符“/”双目运算具有左结合性。参与运算量均为整型时, 结果也为整型,舍去小数。如果运算量中有一个是实型,则结果为双精度实型。 void main(){ printf("\n\n%d,%d\n",20/7,-20/7); printf("%f,%f\n",20.0/7,-20.0/7); } 双目运算具有左结合性。参与运算量均为整型时, 结果也为整型,舍去小数。如果运算量中有一个是实型,则结果为双精度实型。 printf("\n\n%d,%d\n",20/7,-20/7); printf("%f,%f\n",20.0/7,-20.0/7); 本例中,20/7,-20/7的结果均为整型,小数全部舍去。而20.0/7和-20.0/7由于有实数参与运算,因此结果也为实型。 5.求余运算符(模运算符)“%”双目运算,具有左结合性。要求参与运算的量均为整型。 求余运算的结果等于两数相除后的余数。 void main(){ printf("%d\n",100%3); } 双目运算,具有左结合性。求余运算符% 要求参与运算的量均为整型。本例输出100除以3所得的余数1。 自增1,自减1运算符 自增1运算符记为“++”,其功能是使变量的值自增1。自减1运算符记为“--”,其功能是使变量值自减1。自增1,自减1运算符均为单目运算,都具有右结合性。可有以下几种形式: ++i i自增1后再参与其它运算。--i i自减1后再参与其它运算。 i++  i参与运算后,i的值再自增1。 i--  i参与运算后,i的值再自减1。 在理解和使用上容易出错的是i++和i--。 特别是当它们出在较复杂的表达式或语句中时,常常难于弄清,因此应仔细分析。 void main(){ int i=8; printf("%d\n",++i); printf("%d\n",--i); printf("%d\n",i++); printf("%d\n",i--); printf("%d\n",-i++); printf("%d\n",-i--); } i<--8 i<--i+1 i<--i-1 i<--i+1 i<--i-1 i<--i+1 i<--i-1 int i=8; printf("%d\n",++i); printf("%d\n",--i); printf("%d\n",i++); printf("%d\n",i--); printf("%d\n",-i++); printf("%d\n",-i--); i的初值为8 第2行i加1后输出故为9; 第3行减1后输出故为8; 第4行输出i为8之后再加1(为9); 第5行输出i为9之后再减1(为8) ; 第6行输出-8之后再加1(为9); 第7行输出-9之后再减1(为8) void main(){ int i=5,j=5,p,q; p=(i++)+(i++)+(i++); q=(++j)+(++j)+(++j); printf("%d,%d,%d,%d",p,q,i,j); } i<--5,j<--5,p<--0,q<--0 i+i+i--->p,i+1-->i,i+1-->i,i+1-->i j+1->j,j+1->j,j+1->j,j+j+j->q int i=5,j=5,p,q; p=(i++)+(i++)+(i++); q=(++j)+(++j)+(++j); 这个程序中,对P=(i++)+(i++)+(i++)应理解为三个i相加,故P值为15。然后i再自增1三次相当于加3故i的最后值为8。而对于q 的值则不然,q=(++j)+(++j)+(++j)应理解为q先自增1,再参与运算,由于q自增1三次后值为8,三个8相加的和为24,j的最后值仍为8。算术表达式表达式是由常量、变量、函数和运算符组合起来的式子。 一个表达式有一个值及其类型, 它们等于计算表达式所得结果的值和类型。表达式求值按运算符的优先级和结合性规定的顺序进行。 单个的常量、变量、函数可以看作是表达式的特例。 算术表达式 是由算术运算符和括号连接起来的式子, 以下是算术表达式的例子: a+b  (a*2)/c (x+r)*8-(a+b)/7  ++i sin(x)+sin(y)  (++i)-(j++)+(k--) 赋值运算符和赋值表达式 简单赋值运算符和表达式,简单赋值运算符记为“=”。由“= ”连接的式子称为赋值表达式。其一般形式为: 变量=表达式 例如: x=a+b w=sin(a)+sin(b) y=i+++--j 赋值表达式的功能是计算表达式的值再赋予左边的变量。赋值运算符具有右结合性。因此 a=b=c=5 可理解为 a=(b=(c=5)) 在其它高级语言中,赋值构成了一个语句,称为赋值语句。 而在C中,把“=”定义为运算符,从而组成赋值表达式。 凡是表达式可以出现的地方均可出现赋值表达式。例如,式子x=(a=5)+(b=8)是合法的。它的意义是把5赋予a,8赋予b,再把a,b相加,和赋予x ,故x应等于13。 在C语言中也可以组成赋值语句,按照C语言规定, 任何表达式在其未尾加上分号就构成为语句。因此如x=8;a=b=c=5;都是赋值语句,在前面各例中我们已大量使用过了。 如果赋值运算符两边的数据类型不相同, 系统将自动进行类型转换,即把赋值号右边的类型换成左边的类型。具体规定如下: 1.实型赋予整型,舍去小数部分。前面的例2.9已经说明了这种情况。 2.整型赋予实型,数值不变,但将以浮点形式存放, 即增加小数部分(小数部分的值为0)。 3.字符型赋予整型,由于字符型为一个字节, 而整型为二个字节,故将字符的ASCII码值放到整型量的低八位中,高八位为0。 4.整型赋予字符型,只把低八位赋予字符量。 void main(){ int a,b=322; float x,y=8.88; char c1='k',c2; a=y; x=b; a=c1; c2=b; printf("%d,%f,%d,%c",a,x,a,c2); } int a,b=322; float x,y=8.88; char c1='k',c2; printf("%d,%f,%d,%c",a=y,x=b,a=c1,c2=b); 本例表明了上述赋值运算中类型转换的规则。a为整型,赋予实型量y值888后只取整数8。x为实型,赋予整型量b值322, 后增加了小数部分。字符型量c1赋予a变为整型,整型量b赋予c2 后取其低八位成为字符型(b的低八位为01000010,即十进制66,按ASCII码对应于字符B)。 复合赋值符及表达式 在赋值符“=”之前加上其它二目运算符可构成复合赋值符。如 +=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=。 构成复合赋值表达式的一般形式为: 变量 双目运算符=表达式 它等效于 变量=变量 运算符 表达式 例如: a+=5 等价于a=a+5  x*=y+7 等价于x=x*(y+7)  r%=p 等价于r=r%p 复合赋值符这种写法,对初学者可能不习惯, 但十分有利于编译处理,能提高编译效率并产生质量较高的目标代码。逗号运算符和逗号表达式在 逗号运算符 C语言中逗号“,”也是一种运算符,称为逗号运算符。 其功能是把两个表达式连接起来组成一个表达式, 称为逗号表达式。 其一般形式为: 表达式1,表达式2 其求值过程是分别求两个表达式的值,并以表达式2的值作为整个逗号表达式的值。 void main(){ int a=2,b=4,c=6,x,y; y=(x=a+b),(b+c); printf("y=%d,x=%d",y,x); } a<--2,b<--4,c<--6,x<--0,y<--0 x<--a+b,y<---b+c 本例中,y等于整个逗号表达式的值,也就是表达式2的值,x是第一个表达式的值。对于逗号表达式还要说明两点: 1.逗号表达式一般形式中的表达式1和表达式2 也可以又是逗号表达式。例如: 表达式1,(表达式2,表达式3) 形成了嵌套情形。因此可以把逗号表达式扩展为以下形式: 表达式1,表达式2,…表达式n 整个逗号表达式的值等于表达式n的值。 2.程序中使用逗号表达式,通常是要分别求逗号表达式内各表达式的值,并不一定要求整个逗号表达式的值。 3.并不是在所有出现逗号的地方都组成逗号表达式,如在变量说明中,函数参数表中逗号只是用作各变量之间的间隔符。 [Practice] //arithmeticint a,b,c; float d; a=11; b=235; c=a+b-a*b; d=(float)c/(float)a; a=c/a;'Vtable a,2,0 b,2,0 c,2,0 d,4,0.0 of Vtable 'Vupdate 1,0;2,0;3,0 4,0.0 1,11 2,235 3,-2339 4,-212.636368 1,-212 of Vupdate of Practice [Practice] //1int a,b,c1,c2; a=25; b=3243; c1=b/a; c2=b%a;'Vtable a,2,0 b,2,0 c1,2,0 c2,2,0 of Vtable 'Vupdate 1,0;2,0;3,0;4,0 1,25 2,3243 3,129 4,18 of Vupdate of Practice [Practice] //1int a,b,c; a=25; b=40; c=a+b,c+35;'Vtable a,2,0 b,2,0 c,2,0 of Vtable 'Vupdate 1,0;2,0;3,0 1,25 2,40 3,65 of Vupdate of Practice 小结 1.C的数据类型 基本类型,构造类型,指针类型,空类型 2.基本类型的分类及特点 类型说明符      字节       数值范围 字符型char        1        C字符集 基本整型int       2        -32768~32767 短整型short int     2         -32768~32767 长整型 long int     4      -214783648~214783647 无符号型 unsigned    2        0~65535 无符号长整型 unsigned long 4      0~4294967295 单精度实型 float    4       3/4E-38~3/4E+38 双精度实型 double   8       1/7E-308~1/7E+308 3.常量后缀 L或l 长整型 U或u 无符号数 F或f 浮点数 4.常量类型 整数,长整数,无符号数,浮点数,字符,字符串,符号常数,转义字符。 5.数据类型转换 ·自动转换 在不同类型数据的混合运算中,由系统自动实现转换, 由少字节类型向多字节类型转换。 不同类型的量相互赋值时也由系统自动进行转换,把赋值号右边的类型转换为左边的类型。 ·强制转换 由强制转换运算符完成转换。 6.运算符优先级和结合性 一般而言,单目运算符优先级较高,赋值运算符优先级低。 算术运算符优先级较高,关系和逻辑运算符优先级较低。 多数运算符具有左结合性,单目运算符、三目运算符、 赋值 7.表达式 表达式是由运算符连接常量、变量、函数所组成的式子。 每个表达式都有一个值和类型。 表达式求值按运算符的优先级和结合性所规定的顺序进行。 第三章: C语言程序设计初步 C语言程序设计 本课介绍C语言程序设计的基本方法和基本的程序语句。 从程序流程的角度来看,程序可以分为三种基本结构, 即顺序结构、分支结构、循环结构。 这三种基本结构可以组成所有的各种复杂程序。C语言提供了多种语句来实现这些程序结构。 本章介绍这些基本语句及其应用,使读者对C程序有一个初步的认识, 为后面各章的学习打下基础。 C程序的语句 C程序的执行部分是由语句组成的。 程序的功能也是由执行语句实现的。 C语句可分为以下五类: 1.表达式语句 2.函数调用语句 3.控制语句 4.复合语句 5.空语句 1.表达式语句 表达式语句由表达式加上分号“;”组成。其一般形式为: 表达式; 执行表达式语句就是计算表达式的值。例如: x=y+z; 赋值语句y+z; 加法运算语句,但计算结果不能保留,无实际意义i++; 自增1语句,i值增1 2.函数调用语句 由函数名、实际参数加上分号“;”组成。其一般形式为: 函数名(实际参数表); 执行函数语句就是调用函数体并把实际参数赋予函数定义中的形式参数,然后执行被调函数体中的语句,求取函数值。(在第五章函数中再详细介绍)例如printf("C Program");调用库函数,输出字符串。 3.控制语句 控制语句用于控制程序的流程, 以实现程序的各种结构方式。 它们由特定的语句定义符组成。C语言有九种控制语句。 可分成以下三类: (1) 条件判断语句   if语句,switch语句 (2) 循环执行语句   do while语句,while语句,for语句 (3) 转向语句   break语句,goto语句,continue语句,return语句 4.复合语句 把多个语句用括号{}括起来组成的一个语句称复合语句。 在程序中应把复合语句看成是单条语句,而不是多条语句,例如 { x=y+z; a=b+c; printf(“%d%d”,x,a); } 是一条复合语句。复合语句内的各条语句都必须以分号“;”结尾,在括号“}”外不能加分号。 5.空语句 只有分号“;”组成的语句称为空语句。 空语句是什么也不执行的语句。在程序中空语句可用来作空循环体。例如 while(getchar()!='\n'); 本语句的功能是,只要从键盘输入的字符不是回车则重新输入。这里的循环体为空语句。 赋值语句 赋值语句是由赋值表达式再加上分号构成的表达式语句。 其一般形式为: 变量=表达式; 赋值语句的功能和特点都与赋值表达式相同。 它是程序中使用最多的语句之一。 在赋值语句的使用中需要注意以下几点: 1.由于在赋值符“=”右边的表达式也可以又是一个赋值表达式,因此,下述形式 变量=(变量=表达式); 是成立的,从而形成嵌套的情形。其展开之后的一般形式为: 变量=变量=…=表达式; 例如: a=b=c=d=e=5;按照赋值运算符的右接合性,因此实际上等效于: e=5; d=e; c=d; b=c; a=b; 2.注意在变量说明中给变量赋初值和赋值语句的区别。给变量赋初值是变量说明的一部分,赋初值后的变量与其后的其它同类变量之间仍必须用逗号间隔,而赋值语句则必须用分号结尾。 3.在变量说明中,不允许连续给多个变量赋初值。 如下述说明是错误的: int a=b=c=5 必须写为 int a=5,b=5,c=5; 而赋值语句允许连续赋值 4.注意赋值表达式和赋值语句的区别。赋值表达式是一种表达式,它可以出现在任何允许表达式出现的地方,而赋值语句则不能。 下述语句是合法的: if((x=y+5)>0) z=x; 语句的功能是,若表达式x=y+5大于0则z=x。下述语句是非法的: if((x=y+5;)>0) z=x; 因为=y+5;是语句,不能出现在表达式中。 数据输出语句 本小节介绍的是向标准输出设备显示器输出数据的语句。在C语言中,所有的数据输入/输出都是由库函数完成的。 因此都是函数语句。本小节先介绍printf函数和putchar函数。printf函数printf函数称为格式输出函数,其关键字最末一个字母f即为“格式”(format)之意。其功能是按用户指定的格式, 把指定的数据显示到显示器屏幕上。在前面的例题中我们已多次使用过这个函数。 一、printf函数调用的一般形式 printf函数是一个标准库函数,它的函数原型在头文件“stdio.h”中。但作为一个特例,不要求在使用 printf 函数之前必须包含stdio.h文件。printf函数调用的一般形式为: printf(“格式控制字符串”,输出表列)其中格式控制字符串用于指定输出格式。 格式控制串可由格式字符串和非格式字符串两种组成。格式字符串是以%开头的字符串,在%后面跟有各种格式字符,以说明输出数据的类型、形式、长度、小数位数等。如“%d”表示按十进制整型输出,“%ld”表示按十进制长整型输出,“%c”表示按字符型输出等。后面将专门给予讨论。 非格式字符串在输出时原样照印,在显示中起提示作用。 输出表列中给出了各个输出项, 要求格式字符串和各输出项在数量和类型上应该一一对应。 void main() { int a=88,b=89; printf("%d %d\n",a,b); printf("%d,%d\n",a,b); printf("%c,%c\n",a,b); printf("a=%d,b=%d",a,b); } a<--8,b<--89 printf("%d %d\n",a,b); printf("%d,%d\n",a,b); printf("%c,%c\n",a,b); printf("a=%d,b=%d",a,b); 本例中四次输出了a,b的值,但由于格式控制串不同,输出的结果也不相同。第四行的输出语句格式控制串中,两格式串%d 之间加了一个空格(非格式字符),所以输出的a,b值之间有一个空格。第五行的printf语句格式控制串中加入的是非格式字符逗号, 因此输出的a,b值之间加了一个逗号。第六行的格式串要求按字符型输出 a,b值。第七行中为了提示输出结果又增加了非格式字符串。 二、格式字符串 在Turbo C中格式字符串的一般形式为: [标志][输出最小宽度][.精度][长度]类型 其中方括号[]中的项为可选项。各项的意义介绍如下: 1.类型类型字符用以表示输出数据的类型,其格式符和意义下表所示: 表示输出类型的格式字符       格式字符意义 d                 以十进制形式输出带符号整数(正数不输出符号) o                 以八进制形式输出无符号整数(不输出前缀O) x                 以十六进制形式输出无符号整数(不输出前缀OX) u                 以十进制形式输出无符号整数 f                 以小数形式输出单、双精度实数 e                 以指数形式输出单、双精度实数 g                 以%f%e中较短的输出宽度输出单、双精度实数 c                 输出单个字符 s                 输出字符串 2.标志 标志字符为-、+、#、空格四种,其意义下表所示: 标志格式字符      标 志 意 义 -          结果左对齐,右边填空格 +          输出符号(正号或负号)空格输出值为正时冠以空格,为负时冠以负号 #          对c,s,d,u类无影响;对o类, 在输出时加前 缀o         对x类,在输出时加前缀0x;对e,g,f 类当结果有小数时才给出小数点 3.输出最小宽度 用十进制整数来表示输出的最少位数。 若实际位数多于定义的宽度,则按实际位数输出, 若实际位数少于定义的宽度则补以空格或0。 4.精度 精度格式符以“.”开头,后跟十进制整数。本项的意义是:如果输出数字,则表示小数的位数;如果输出的是字符, 则表示输出字符的个数;若实际位数大于所定义的精度数,则截去超过的部分。 5.长度 长度格式符为h,l两种,h表示按短整型量输出,l表示按长整型量输出。 void main(){ int a=15; float b=138.3576278; double c=35648256.3645687; char d='p'; printf("a=%d,%5d,%o,%x\n",a,a,a,a); printf("b=%f,%lf,%5.4lf,%e\n",b,b,b,b); printf("c=%lf,%f,%8.4lf\n",c,c,c); printf("d=%c,%8c\n",d,d); } a<--15 b<--138.3576278 c<--35648256.3645687 d<--'p' main() { int a=29; float b=1243.2341; double c=24212345.24232; char c='h' printf("a=%d,%5d,%o,%x\n",a,a,a,a); printf("b=%f,%lf,%5.4lf,%e\n",b,b,b,b); printf("c=%lf,%f,%8.4lf\n",c,c,c); printf("d=%c,%8c\n",d,d); } 本例第七行中以四种格式输出整型变量a的值,其中“%5d ”要求输出宽度为5,而a值为15只有两位故补三个空格。 第八行中以四种格式输出实型量b的值。其中“%f”和“%lf ”格式的输出相同,说明“l”符对“f”类型无影响。“%5.4lf”指定输出宽度为5,精度为4,由于实际长度超过5故应该按实际位数输出,小数位数超过4位部分被截去。第九行输出双精度实数,“%8.4lf ”由于指定精度为4位故截去了超过4位的部分。第十行输出字符量d,其中“%bc ”指定输出宽度为8故在输出字符p之前补加7个空格。 使用printf函数时还要注意一个问题, 那就是输出表列中的求值顺序。不同的编译系统不一定相同,可以从左到右, 也可从右到左。Turbo C是按从右到左进行的。如把例2.13改写如下述形式: void main(){ int i=8; printf("%d\n%d\n%d\n%d\n%d\n%d\n",++i,--i,i--,i++,-i--); } i<--8 这个程序与例2.13相比只是把多个printf语句改一个printf 语句输出。但从结果可以看出是不同的。为什么结果会不同呢?就是因为printf函数对输出表中各量求值的顺序是自右至左进行 的。在式中,先对最后一项“-i--”求值,结果为-8,然后i自减1后为7。 再对“-i++”项求值得-7,然后i自增1后为8。再对“i--”项求值得8,然后i再自减1后为7。再求“i++”项得7,然后I再自增1后为8。 再求“--i”项,i先自减1后输出,输出值为7。 最后才求输出表列中的第一项“++i”,此时i自增1后输出8。但是必须注意, 求值顺序虽是自右至左,但是输出顺序还是从左至右, 因此得到的结果是上述输出结果。 字符输出函数 putchar 函数 putchar 函数是字符输出函数, 其功能是在显示器上输出单个字符。其一般形式为: putchar(字符变量) 例如: putchar('A'); 输出大写字母A putchar(x); 输出字符变量x的值 putchar('\n'); 换行 对控制字符则执行控制功能,不在屏幕上显示。 使用本函数前必须要用文件包含命令: #include #include void main(){ char a='B',b='o',c='k'; putchar(a);putchar(b);putchar(b);putchar(c);putchar('\t'); putchar(a);putchar(b); putchar('\n'); putchar(b);putchar(c); } 数据输入语句 C语言的数据输入也是由函数语句完成的。 本节介绍从标准输入设备—键盘上输入数据的函数scanf和getchar。 scanf函数 scanf函数称为格式输入函数,即按用户指定的格式从键盘上把数据输入到指定的变量之中。 一、scanf函数的一般形式 scanf函数是一个标准库函数,它的函数原型在头文件“stdio.h”中,与printf函数相同,C语言也允许在使用scanf函数之前不必包含stdio.h文件。scanf函数的一般形式为: scanf(“格式控制字符串”,地址表列); 其中,格式控制字符串的作用与printf函数相同,但不能显示非格式字符串, 也就是不能显示提示字符串。地址表列中给出各变量的地址。 地址是由地址运算符“&”后跟变量名组成的。例如,&a,&b分别表示变量a和变量b 的地址。这个地址就是编译系统在内存中给a,b变量分配的地址。在C语言中,使用了地址这个概念,这是与其它语言不同的。 应该把变量的值和变量的地址这两个不同的概念区别开来。变量的地址是C编译系统分配的,用户不必关心具体的地址是多少。 变量的地址和变量值的关系如下: &a--->a567 a为变量名,567是变量的值,&a是变量a的地址。在赋值表达式中给变量赋值,如: a=567 在赋值号左边是变量名,不能写地址,而scanf函数在本质上也是给变量赋值,但要求写变量的地址,如&a。 这两者在形式上是不同的。&是一个取地址运算符,&a是一个表达式,其功能是求变量的地址。 void main(){ int a,b,c; printf("input a,b,c\n"); scanf("%d%d%d",&a,&b,&c); printf("a=%d,b=%d,c=%d",a,b,c); } 注意&的用法! 在本例中,由于scanf函数本身不能显示提示串,故先用printf语句在屏幕上输出提示,请用户输入a、b、c的值。执行scanf语句,则退出TC屏幕进入用户屏幕等待用户输入。用户输入7、8、9后按下回车键,此时,系统又将返回TC屏幕。在scanf语句的格式串中由于没有非格式字符在“%d%d%d”之间作输入时的间隔, 因此在输入时要用一个以上的空格或回车键作为每两个输入数之间的间隔。 如: 7 8 9 或 7 8 9 格式字符串 格式字符串的一般形式为: %[*][输入数据宽度][长度]类型 其中有方括号[]的项为任选项。各项的意义如下: 1.类型 表示输入数据的类型,其格式符和意义下表所示。 格式    字符意义 d     输入十进制整数 o     输入八进制整数 x     输入十六进制整数 u     输入无符号十进制整数 f或e    输入实型数(用小数形式或指数形式) c     输入单个字符 s     输入字符串 2.“*”符 用以表示该输入项读入后不赋予相应的变量,即跳过该输入值。 如 scanf("%d %*d %d",&a,&b);当输入为:1 2 3 时,把1赋予a,2被跳过,3赋予b。 3.宽度 用十进制整数指定输入的宽度(即字符数)。例如: scanf("%5d",&a); 输入: 12345678 只把12345赋予变量a,其余部分被截去。又如: scanf("%4d%4d",&a,&b); 输入: 12345678将把1234赋予a,而把5678赋予b。 4.长度 长度格式符为l和h,l表示输入长整型数据(如%ld) 和双精度浮点数(如%lf)。h表示输入短整型数据。 使用scanf函数还必须注意以下几点: a. scanf函数中没有精度控制,如: scanf("%5.2f",&a); 是非法的。不能企图用此语句输入小数为2位的实数。 b. scanf中要求给出变量地址,如给出变量名则会出错。如 scanf("%d",a);是非法的,应改为scnaf("%d",&a);才是合法的。 c. 在输入多个数值数据时,若格式控制串中没有非格式字符作输入数据之间的间隔则可用空格,TAB或回车作间隔。C编译在碰到空格,TAB,回车或非法数据(如对“%d”输入“12A”时,A即为非法数据)时即认为该数据结束。 d. 在输入字符数据时,若格式控制串中无非格式字符,则认为所有输入的字符均为有效字符。例如: scanf("%c%c%c",&a,&b,&c); 输入为: d e f 则把'd'赋予a, 'f'赋予b,'e'赋予c。只有当输入为: def 时,才能把'd'赋于a,'e'赋予b,'f'赋予c。 如果在格式控制中加入空格作为间隔,如 scanf ("%c %c %c",&a,&b,&c);则输入时各数据之间可加空格。 void main(){ char a,b; printf("input character a,b\n"); scanf("%c%c",&a,&b); printf("%c%c\n",a,b); } scanf("'C14F14%c%c",&a,&b); printf("%c%c\n",a,b); 由于scanf函数"%c%c"中没有空格,输入M N,结果输出只有M。 而输入改为MN时则可输出MN两字符,见下面的输入运行情况: input character a,b MN MN void main(){ char a,b; printf("input character a,b\n"); scanf("%c %c",&a,&b); printf("\n%c%c\n",a,b); } scanf("%c %c",&a,&b); 本例表示scanf格式控制串"%c %c"之间有空格时, 输入的数据之间可以有空格间隔。e. 如果格式控制串中有非格式字符则输入时也要输入该非格式字符。 例如: scanf("%d,%d,%d",&a,&b,&c); 其中用非格式符“ , ”作间隔符,故输入时应为: 5,6,7 又如: scanf("a=%d,b=%d,c=%d",&a,&b,&c); 则输入应为 a=5,b=6,c=7g. 如输入的数据与输出的类型不一致时,虽然编译能够通过,但结果将不正确。 void main(){ int a; printf("input a number\n"); scanf("%d",&a); printf("%ld",a); } 由于输入数据类型为整型, 而输出语句的格式串中说明为长整型,因此输出结果和输入数据不符。如改动程序如下: void main(){ long a; printf("input a long integer\n"); scanf("%ld",&a); printf("%ld",a); } 运行结果为: input a long integer 1234567890 1234567890 当输入数据改为长整型后,输入输出数据相等。 键盘输入函数 getchar函数getchar函数的功能是从键盘上输入一个字符。其一般形式为: getchar(); 通常把输入的字符赋予一个字符变量,构成赋值语句,如: char c; c=getchar();#include void main(){ char c; printf("input a character\n"); c=getchar(); putchar(c); } 使用getchar函数还应注意几个问题: 1.getchar函数只能接受单个字符,输入数字也按字符处理。输入多于一个字符时,只接收第一个字符。 2.使用本函数前必须包含文件“stdio.h”。 3.在TC屏幕下运行含本函数程序时,将退出TC 屏幕进入用户屏幕等待用户输入。输入完毕再返回TC屏幕。 void main(){ char a,b,c; printf("input character a,b,c\n"); scanf("%c %c %c",&a,&b,&c); printf("%d,%d,%d\n%c,%c,%c\n",a,b,c,a-32,b-32,c-32); } 输入三个小写字母 输出其ASCII码和对应的大写字母。 void main(){ int a; long b; float f; double d; char c; printf("%d,%d,%d,%d,%d",sizeof(a),sizeof(b),sizeof(f) ,sizeof(d),sizeof(c)); } 输出各种数据类型的字节长度。 分支结构程序 关系运算符和表达式 在程序中经常需要比较两个量的大小关系, 以决定程序下一步的工作。比较两个量的运算符称为关系运算符。 在C语言中有以下关系运算符: < 小于 <= 小于或等于 > 大于 >= 大于或等于 == 等于 != 不等于 关系运算符都是双目运算符,其结合性均为左结合。 关系运算符的优先级低于算术运算符,高于赋值运算符。 在六个关系运算符中,<,<=,>,>=的优先级相同,高于==和!=,==和!=的优先级相同。 关系表达式 关系表达式的一般形式为: 表达式 关系运算符 表达式 例如:a+b>c-d,x>3/2,'a'+1(b>c),a!=(c==d)等。关系表达式的值是“真”和“假”,用“1”和“0”表示。 如: 5>0的值为“真”,即为1。(a=3)>(b=5)由于3>5不成立,故其值为假,即为0。 void main(){ char c='k'; int i=1,j=2,k=3; float x=3e+5,y=0.85; printf("%d,%d\n",'a'+5=k+1); printf("%d,%d\n",1=k+1); printf("%d,%d\n",1b && c>d等价于(a>b) && (c>d) !b==c||dc && x+yc) && ((x+y)0 && 4>2,由于5>0为真,4>2也为真,相与的结果也为真。 2.或运算||参与运算的两个量只要有一个为真,结果就为真。 两个量都为假时,结果为假。例如:5>0||5>8,由于5>0为真,相或的结果也就为真 3.非运算!参与运算量为真时,结果为假;参与运算量为假时,结果为真。 例如:!(5>0)的结果为假。 虽然C编译在给出逻辑运算值时,以“1”代表“真”,“0 ”代表“假”。 但反过来在判断一个量是为“真”还是为“假”时,以“0”代表“假”,以非“0”的数值作为“真”。例如:由于5和3均为非“0”因此5&&3的值为“真”,即为1。 又如:5||0的值为“真”,即为1。 逻辑表达式逻辑表达式的一般形式为: 表达式 逻辑运算符 表达式 其中的表达式可以又是逻辑表达式,从而组成了嵌套的情形。例如:(a&&b)&&c根据逻辑运算符的左结合性,上式也可写为: a&&b&&c 逻辑表达式的值是式中各种逻辑运算的最后值,以“1”和“0”分别代表“真”和“假”。 void main(){ char c='k'; int i=1,j=2,k=3; float x=3e+5,y=0.85; printf("%d,%d\n",!x*!y,!!!x); printf("%d,%d\n",x||i&&j-3,ib) printf("max=%d\n",a); else printf("max=%d\n",b); } 输入两个整数,输出其中的大数。改用if-else语句判别a,b的大小,若a大,则输出a,否则输出b。 3.第三种形式为if-else-if形式 前二种形式的if语句一般都用于两个分支的情况。 当有多个分支选择时,可采用if-else-if语句,其一般形式为: if(表达式1) 语句1; else if(表达式2) 语句2; else if(表达式3) 语句3; … else if(表达式m) 语句m; else 语句n; 其语义是:依次判断表达式的值,当出现某个值为真时, 则执行其对应的语句。然后跳到整个if语句之外继续执行程序。 如果所有的表达式均为假,则执行语句n 。 然后继续执行后续程序。 if-else-if语句的执行过程如图3—3所示。 #include"stdio.h" void main(){ char c; printf("input a character: "); c=getchar(); if(c<32) printf("This is a control character\n"); else if(c>='0'&&c<='9') printf("This is a digit\n"); else if(c>='A'&&c<='Z') printf("This is a capital letter\n"); else if(c>='a'&&c<='z') printf("This is a small letter\n"); else printf("This is an other character\n"); } if(c<32) printf("This is a control character\n"); else if(c>='0'&&c<='9') printf("This is a digit\n"); else if(c>='A'&&c<='Z') printf("This is a capital letter\n"); else if(c>='a'&&c<='z') printf("This is a small letter\n"); else printf("This is an other character\n"); 本例要求判别键盘输入字符的类别。可以根据输入字符的ASCII码来判别类型。由ASCII码表可知ASCII值小于32的为控制字符。 在“0”和“9”之间的为数字,在“A”和“Z”之间为大写字母, 在“a”和“z”之间为小写字母,其余则为其它字符。 这是一个多分支选择的问题,用if-else-if语句编程,判断输入字符ASCII码所在的范围,分别给出不同的输出。例如输入为“g”,输出显示它为小写字符。 4.在使用if语句中还应注意以下问题 (1) 在三种形式的if语句中,在if关键字之后均为表达式。 该表达式通常是逻辑表达式或关系表达式, 但也可以是其它表达式,如赋值表达式等,甚至也可以是一个变量。例如: if(a=5) 语句;if(b) 语句; 都是允许的。只要表达式的值为非0,即为“真”。如在if(a=5)…;中表达式的值永远为非0,所以其后的语句总是要执行的,当然这种情况在程序中不一定会出现,但在语法上是合法的。 又如,有程序段: if(a=b) printf("%d",a); else printf("a=0"); 本语句的语义是,把b值赋予a,如为非0则输出该值,否则输出“a=0”字符串。这种用法在程序中是经常出现的。 (2) 在if语句中,条件判断表达式必须用括号括起来, 在语句之后必须加分号。 (3) 在if语句的三种形式中,所有的语句应为单个语句,如果要想在满足条件时执行一组(多个)语句,则必须把这一组语句用{} 括起来组成一个复合语句。但要注意的是在}之后不能再加分号。 例如: if(a>b){ a++; b++; } else{ a=0; b=10; } if语句的嵌套 当if语句中的执行语句又是if语句时,则构成了if 语句嵌套的情形。其一般形式可表示如下: if(表达式) if语句; 或者为 if(表达式) if语句; else if语句; 在嵌套内的if语句可能又是if-else型的,这将会出现多个if和多个else重叠的情况,这时要特别注意if和else的配对问题。例如: if(表达式1) if(表达式2) 语句1; else 语句2; 其中的else究竟是与哪一个if配对呢? 应该理解为:   还是应理解为: if(表达式1)    if(表达式1)  if(表达式2)     if(表达式2)   语句1;       语句1; else         else   语句2;       语句2; 为了避免这种二义性,C语言规定,else 总是与它前面最近的if配对,因此对上述例子应按前一种情况理解。 void main(){ int a,b; printf("please input A,B: "); scanf("%d%d",&a,&b); if(a!=b) if(a>b) printf("A>B\n"); else printf("Ab) printf("A>B\n"); else printf("AB、Ab) printf("A>B\n"); else printf("Ab) max=a; else max=b; 可用条件表达式写为 max=(a>b)?a:b; 执行该语句的语义是:如a>b为真,则把a赋予max,否则把b 赋予max。 使用条件表达式时,还应注意以下几点: 1. 条件运算符的运算优先级低于关系运算符和算术运算符,但高于赋值符。因此 max=(a>b)?a:b可以去掉括号而写为 max=a>b?a:b 2. 条件运算符?和:是一对运算符,不能分开单独使用。 3. 条件运算符的结合方向是自右至左。 例如: a>b?a:c>d?c:d应理解为 a>b?a:(c>d?c:d) 这也就是条件表达式嵌套的情形,即其中的表达式3又是一个条 件表达式。 void main(){ int a,b,max; printf("\n input two numbers: "); scanf("%d%d",&a,&b); printf("max=%d",a>b?a:b); } 用条件表达式对上例重新编程,输出两个数中的大数。 switch语句 C语言还提供了另一种用于多分支选择的switch语句, 其一般形式为: switch(表达式){ case常量表达式1: 语句1; case常量表达式2: 语句2; … case常量表达式n: 语句n; default : 语句n+1; } 其语义是:计算表达式的值。 并逐个与其后的常量表达式值相比较,当表达式的值与某个常量表达式的值相等时, 即执行其后的语句,然后不再进行判断,继续执行后面所有case后的语句。 如表达式的值与所有case后的常量表达式均不相同时,则执行default后的语句。 void main(){ int a; printf("input integer number: "); scanf("%d",&a); switch (a){ case 1:printf("Monday\n"); case 2:printf("Tuesday\n"); case 3:printf("Wednesday\n"); case 4:printf("Thursday\n"); case 5:printf("Friday\n"); case 6:printf("Saturday\n"); case 7:printf("Sunday\n"); default:printf("error\n"); } } 本程序是要求输入一个数字,输出一个英文单词。但是当输入3之后,却执行了case3以及以后的所有语句,输出了Wednesday 及以后的所有单词。这当然是不希望的。为什么会出现这种情况呢?这恰恰反应了switch语句的一个特点。在switch语句中,“case 常量表达式”只相当于一个语句标号, 表达式的值和某标号相等则转向该标号执行,但不能在执行完该标号的语句后自动跳出整个switch 语句,所以出现了继续执行所有后面case语句的情况。 这是与前面介绍的if语句完全不同的,应特别注意。为了避免上述情况, C语言还提供了一种break语句,专用于跳出switch语句,break 语句只有关键字break,没有参数。在后面还将详细介绍。修改例题的程序,在每一case语句之后增加break 语句, 使每一次执行之后均可跳出switch语句,从而避免输出不应有的结果。 void main(){ int a; printf("input integer number: "); scanf("%d",&a); switch (a){ case 1:printf("Monday\n");break; case 2:printf("Tuesday\n"); break; case 3:printf("Wednesday\n");break; case 4:printf("Thursday\n");break; case 5:printf("Friday\n");break; case 6:printf("Saturday\n");break; case 7:printf("Sunday\n");break; default:printf("error\n"); } } 在使用switch语句时还应注意以下几点: 1.在case后的各常量表达式的值不能相同,否则会出现错误。 2.在case后,允许有多个语句,可以不用{}括起来。 3.各case和default子句的先后顺序可以变动,而不会影响程序执行结果。 4.default子句可以省略不用。程序举例 输入三个整数,输出最大数和最小数。 void main(){ int a,b,c,max,min; printf("input three numbers: "); scanf("%d%d%d",&a,&b,&c); if(a>b) {max=a;min=b;} else {max=b;min=a;} if(maxc) min=c; printf("max=%d\nmin=%d",max,min); } 本程序中,首先比较输入的a,b的大小,并把大数装入max, 小数装入min中,然后再与c比较,若max小于c,则把c赋予max;如果c小于min,则把c赋予min。因此max内总是最大数,而min内总是最小数。最后输出max和min的值即可。 计算器程序。用户输入运算数和四则运算符, 输出计算结果。 void main(){ float a,b,s; char c; printf("input expression: a+(-,*,/)b \n"); scanf("%f%c%f",&a,&c,&b); switch(c){ case '+': printf("%f\n",a+b);break; case '-': printf("%f\n",a-b);break; case '*': printf("%f\n",a*b);break; case '/': printf("%f\n",a/b);break; default: printf("input error\n"); } } float a,b,s; char c; printf("input expression: a+(-,*,/)b \n"); scanf("%f%c%f",&a,&c,&b); switch(c){ case '+': printf("%f\n",a+b);break; case '-': printf("%f\n",a-b);break; case '*': printf("%f\n",a*b);break; case '/': printf("%f\n",a/b);break; default: printf("input error\n"); } 本例可用于四则运算求值。switch语句用于判断运算符, 然后输出运算值。当输入运算符不是+,-,*,/时给出错误提示。 循环结构程序 循环结构是程序中一种很重要的结构。其特点是, 在给定条件成立时,反复执行某程序段,直到条件不成立为止。 给定的条件称为循环条件,反复执行的程序段称为循环体。 C语言提供了多种循环语句,可以组成各种不同形式的循环结构。 while语句 while语句的一般形式为: while(表达式)语句; 其中表达式是循环条件,语句为循环体。 while语句的语义是:计算表达式的值,当值为真(非0)时, 执行循环体语句。其执行过程可用图3—4表示。 统计从键盘输入一行字符的个数。 #include void main(){ int n=0; printf("input a string:\n"); while(getchar()!='\n') n++; printf("%d",n); } int n=0; printf("input a string:\n"); while(getchar()!='\n') n++; printf("%d",n); 本例程序中的循环条件为getchar()!='\n',其意义是, 只要从键盘输入的字符不是回车就继续循环。循环体n++完成对输入字符个数计数。从而程序实现了对输入一行字符的字符个数计数。 使用while语句应注意以下几点: 1.while语句中的表达式一般是关系表达或逻辑表达式,只要表达式的值为真(非0)即可继续循环。 void main(){ int a=0,n; printf("\n input n: "); scanf("%d",&n); while (n--) printf("%d ",a++*2); } int a=0,n; printf("\n input n: "); scanf("%d",&n); while (n--) printf("%d ",a++*2); 本例程序将执行n次循环,每执行一次,n值减1。循环体输出表达式a++*2的值。该表达式等效于(a*2;a++) 2.循环体如包括有一个以上的语句,则必须用{}括起来, 组成复合语句。 3.应注意循环条件的选择以避免死循环。 void main(){ int a,n=0; while(a=5) printf("%d ",n++); } int a,n=0; while(a=5) printf("%d ",n++); 本例中while语句的循环条件为赋值表达式a=5, 因此该表达式的值永远为真,而循环体中又没有其它中止循环的手段, 因此该循环将无休止地进行下去,形成死循环。4.允许while语句的循环体又是while语句,从而形成双重循环。 do-while语句 do-while语句的一般形式为: do 语句; while(表达式); 其中语句是循环体,表达式是循环条件。 do-while语句的语义是: 先执行循环体语句一次, 再判别表达式的值,若为真(非0)则继续循环,否则终止循环。 do-while语句和while语句的区别在于do-while是先执行后判断,因此do-while至少要执行一次循环体。而while是先判断后执行,如果条件不满足,则一次循环体语句也不执行。 while语句和do-while语句一般都可以相互改写。 void main(){ int a=0,n; printf("\n input n: "); scanf("%d",&n); do printf("%d ",a++*2); while (--n); } int a=0,n; printf("\n input n: "); scanf("%d",&n); do printf("%d ",a++*2); while (--n); 在本例中,循环条件改为--n,否则将多执行一次循环。这是由于先执行后判断而造成的。 对于do-while语句还应注意以下几点: 1.在if语句,while语句中, 表达式后面都不能加分号, 而在 do-while语句的表达式后面则必须加分号。 2.do-while语句也可以组成多重循环,而且也可以和while语句相互嵌套。 3.在do和while之间的循环体由多个语句组成时,也必须用{}括起来组成一个复合语句。 4.do-while和while语句相互替换时,要注意修改循环控制条件。 for语句 for语句是C语言所提供的功能更强,使用更广泛的一种循环语句。其一般形式为: for(表达式1;表达式2;表达3) 语句; 表达式1 通常用来给循环变量赋初值,一般是赋值表达式。也允许在for语句外给循环变量赋初值,此时可以省略该表达式。 表达式2 通常是循环条件,一般为关系表达式或逻辑表达式。 表达式3 通常可用来修改循环变量的值,一般是赋值语句。 这三个表达式都可以是逗号表达式, 即每个表达式都可由多个表达式组成。三个表达式都是任选项,都可以省略。 一般形式中的“语句”即为循环体语句。for语句的语义是: 1.首先计算表达式1的值。 2.再计算表达式2的值,若值为真(非0)则执行循环体一次, 否则跳出循环。 3.然后再计算表达式3的值,转回第2步重复执行。在整个for循环过程中,表达式1只计算一次,表达式2和表达式,3则可能计算多次。循环体可能多次执行,也可能一次都不执行。for 语句的执行过程如图所示。 void main(){ int n,s=0; for(n=1;n<=100;n++) s=s+n; printf("s=%d\n",s); } 用for语句计算s=1+2+3+...+99+100 int n,s=0; for(n=1;n<=100;n++) s=s+n; printf("s=%d\n",s); 本例for语句中的表达式3为n++,实际上也是一种赋值语句,相当于n=n+1,以改变循环变量的值。 void main(){ int a=0,n; printf("\n input n: "); scanf("%d",&n); for(;n>0;a++,n--) printf("%d ",a*2); } 用for语句修改例题。从0开始,输出n个连续的偶数。 int a=0,n; printf("\n input n: "); scanf("%d",&n); for(;n>0;a++,n--) printf("%d ",a*2); 本例的for语句中,表达式1已省去,循环变量的初值在for语句之前由scanf语句取得,表达式3是一个逗号表达式,由a++,n-- 两个表达式组成。每循环一次a自增1,n自减1。a的变化使输出的偶数递增,n的变化控制循次数。 在使用for语句中要注意以下几点 1.for语句中的各表达式都可省略,但分号间隔符不能少。如:for(;表达式;表达式)省去了表达式1。for(表达式;;表达式)省去了表达式2。 for(表达式;表达式;)省去了表达式3。for(;;)省去了全部表达式。 2.在循环变量已赋初值时,可省去表达式1,如例3.27即属于这种情形。如省去表达式2或表达式3则将造成无限循环, 这时应在循环体内设法结束循环。例题即属于此情况。 void main(){ int a=0,n; printf("\n input n: "); scanf("%d",&n); for(;n>0;) { a++;n--; printf("%d ",a*2); } } int a=0,n; printf("\n input n: "); scanf("%d",&n); for(;n>0;) { a++;n--; printf("%d ",a*2); } 本例中省略了表达式1和表达式3,由循环体内的n--语句进行循环变量n的递减,以控制循环次数。 void main(){ int a=0,n; printf("\n input n: "); scanf("%d",&n); for(;;){ a++;n--; printf("%d ",a*2); if(n==0)break; } } int a=0,n; printf("\n input n: "); scanf("%d",&n); for(;;){ a++;n--; printf("%d ",a*2); if(n==0)break; } 本例中for语句的表达式全部省去。由循环体中的语句实现循环变量的递减和循环条件的判断。当n值为0时,由break语句中止循环,转去执行for以后的程序。在此情况下,for语句已等效于while( 1)语句。如在循环体中没有相应的控制手段,则造成死循环。 3.循环体可以是空语句。 #include"stdio.h" void main(){ int n=0; printf("input a string:\n"); for(;getchar()!='\n';n++); printf("%d",n); } 本例中,省去了for语句的表达式1,表达式3也不是用来修改循环变量,而是用作输入字符的计数。这样, 就把本应在循环体中完成的计数放在表达式中完成了。因此循环体是空语句。应注意的是,空语句后的分号不可少,如缺少此分号,则把后面的printf 语句当成循环体来执行。反过来说,如循环体不为空语句时, 决不能在表达式的括号后加分号, 这样又会认为循环体是空语句而不能反复执行。这些都是编程中常见的错误,要十分注意。 4.for语句也可与while,do-while语句相互嵌套,构成多重循环。以下形成都合法的嵌套。 (1)for(){…   while()    {…}   …     } (2)do{    …   for()    {…}   …   }while(); (3)while(){       …       for()        {…}       …      } (4)for(){     …     for(){     …      }     } void main(){ int i,j,k; for(i=1;i<=3;i++) { for(j=1;j<=3-i+5;j++) printf(" "); for(k=1;k<=2*i-1+5;k++) { if(k<=5) printf(" "); else printf("*"); } printf("\n"); } } 转移语句 程序中的语句通常总是按顺序方向, 或按语句功能所定义的方向执行的。如果需要改变程序的正常流向, 可以使用本小节介绍的转移语句。在C语言中提供了4种转移语句: goto,break, continue和return。 其中的return语句只能出现在被调函数中, 用于返回主调函数,我们将在函数一章中具体介绍。 本小节介绍前三种转移语句。 1.goto语句 goto语句也称为无条件转移语句,其一般格式如下: goto 语句标号; 其中语句标号是按标识符规定书写的符号, 放在某一语句行的 前面,标号后加冒号(:)。语句标号起标识语句的作用,与goto 语句配合使用。 如: label: i++; loop: while(x<7); C语言不限制程序中使用标号的次数,但各标号不得重名。goto语句的语义是改变程序流向, 转去执行语句标号所标识的语句。 goto语句通常与条件语句配合使用。可用来实现条件转移, 构成循环,跳出循环体等功能。 但是,在结构化程序设计中一般不主张使用goto语句, 以免造成程序流程的混乱,使理解和调试程序都产生困难。 统计从键盘输入一行字符的个数。 #include"stdio.h" void main(){ int n=0; printf("input a string\n"); loop: if(getchar()!='\n') { n++; goto loop; } printf("%d",n); } int n=0; printf("input a string\n"); loop: if(getchar()!='\n') { n++; goto loop; } printf("%d",n); 本例用if语句和goto语句构成循环结构。当输入字符不为'\n'时即执行n++进行计数,然后转移至if语句循环执行。直至输入字符为'\n'才停止循环。 break语句 break语句只能用在switch 语句或循环语句中, 其作用是跳出switch语句或跳出本层循环,转去执行后面的程序。由于break语句的转移方向是明确的,所以不需要语句标号与之配合。break语句的一般形式为: break; 上面例题中分别在switch语句和for语句中使用了break 语句作为跳转。使用break语句可以使循环语句有多个出口,在一些场合下使编程更加灵活、方便。 continue语句 continue语句只能用在循环体中,其一般格式是: continue; 其语义是:结束本次循环,即不再执行循环体中continue 语句之后的语句,转入下一次循环条件的判断与执行。应注意的是, 本语句只结束本层本次的循环,并不跳出循环。 void main(){ int n; for(n=7;n<=100;n++) { if (n%7!=0) continue; printf("%d ",n); } } 输出100以内能被7整除的数。 int n; for(n=7;n<=100;n++) { if (n%7!=0) continue; printf("%d ",n); } 本例中,对7~100的每一个数进行测试,如该数不能被7整除,即模运算不为0,则由continus语句转去下一次循环。只有模运算为0时,才能执行后面的printf语句,输出能被7整除的数。 #include"stdio.h" void main(){ char a,b; printf("input a string:\n"); b=getchar(); while((a=getchar())!='\n'){ if(a==b){ printf("same character\n"); break; }b=a; } } 检查输入的一行中有无相邻两字符相同。 char a,b; printf("input a string:\n"); b=getchar(); while((a=getchar())!='\n'){ if(a==b){ printf("same character\n"); break; }b=a; } 本例程序中,把第一个读入的字符送入b。然后进入循环,把下一字符读入a,比较a,b是否相等,若相等则输出提示串并中止循环,若不相等则把a中的字符赋予b,输入下一次循环。 输出100以内的素数。素数是只能被1 和本身整除的数。可用穷举法来判断一个数是否是素数。 void main(){ int n,i; for(n=2;n<=100;n++){ for(i=2;i=n) printf("\t%d",n); } } int n,i; for(n=2;n<=100;n++){ for(i=2;i=n) printf("\t%d",n); } 本例程序中,第一层循环表示对1~100这100个数逐个判断是否是素数,共循环100次,在第二层循环中则对数n用2~n-1逐个去除,若某次除尽则跳出该层循环,说明不是素数。 如果在所有的数都是未除尽的情况下结束循环,则为素数,此时有i>=n, 故可经此判断后输出素数。然后转入下一次大循环。实际上,2以上的所有偶数均不是素数,因此可以使循环变量的步长值改为2,即每次增加2,此外只需对数n用2~n去除就可判断该数是否素数。这样将大大减少循环次数,减少程序运行时间。 #include"math.h" void main(){ int n,i,k; for(n=2;n<=100;n+=2){ k=sqrt(n); for(i=2;i=k) printf("\t%2d",n); } } 小结 1.从程序执行的流程来看, 程序可分为三种最基本的结构: 顺序结构,分支结构以及循环结构 2.程序中执行部分最基本的单位是语句。C语言的语句可分为五类: (1)表达式语句  任何表达式末尾加上分号即可构成表达式语句, 常用的表达式语句为赋值语句。 (2)函数调用语句  由函数调用加上分号即组成函数调用语句。 (3)控制语句  用于控制程序流程,由专门的语句定义符及所需的表达式组成。主要有条件判断执行语句,循环执行语句,转向语句等。 (4)复合语句  由{}把多个语句括起来组成一个语句。 复合语句被认为是单条语句,它可出现在所有允许出现语句的地方,如循环体等。 (5)空语句  仅由分号组成,无实际功能。 3.C语言中没有提供专门的输入输出语句, 所有的输入输出都是由调用标准库函数中的输入输出函数来实现的。 scanf和getchar函数是输入函数,接收来自键盘的输入数据。 scanf是格式输入函数, 可按指定的格式输入任意类型数据。 getchar函数是字符输入函数, 只能接收单个字符。 printf和putchar函数是输出函数,向显示器屏幕输出数据。 printf是格式输出函数,可按指定的格式显示任意类型的数据。 putchar是字符显示函数,只能显示单个字符。 4.关系表达式和逻辑表达式是两种重要的表达式, 主要用于条件执行的判断和循环执行的判断。 5.C语言提供了多种形式的条件语句以构成分支结构。 (1)if语句主要用于单向选择。 (2)if-else语句主要用于双向选择。 (3)if-else-if语和switch语句用于多向选择。 这几种形式的条件语句一般来说是可以互相替代的。 6.C语言提供了三种循环语句。 (1)for语句主要用于给定循环变量初值, 步长增量以及循环次数的循环结构。 (2)循环次数及控制条件要在循环过程中才能确定的循环可用 while或do-while语句。 (3)三种循环语句可以相互嵌套组成多重循环。循环之间可以并列但不能交叉。 (4)可用转移语句把流程转出循环体外,但不能从外面转向循环体内。 (5)在循环程序中应避免出现死循环,即应保证循环变量的值在运行过程中可以得到修改,并使循环条件逐步变为假,从而结束循环。 7.C语言语句小结 名 称         一 般 形 式 简单语句       表达式语句表达式; 空语句; 复合语句        { 语句 } 条件语句       if(表达式)语句;            if(表达式)语句1; else语句2;            if(表达式1)语句1; else if(表达式2) 语句2…else语句 n; 开关语句        switch(表达式){ case常量表达式: 语句…default: 语句; } 循环语句       while语句            while(表达式)语句;            for语句 for(表达式1; 表达式2; 表达式3)语句;            break语句 break;            goto语句 goto;            continue语句 continue;            return 语句 return(表达式); 第四章: 数组 数 组   数组在程序设计中,为了处理方便, 把具有相同类型的若干变量按有序的形式组织起来。这些按序排列的同类数据元素的集合称为数组。在C语言中, 数组属于构造数据类型。一个数组可以分解为多个数组元素,这些数组元素可以是基本数据类型或是构造类型。因此按数组元素的类型不同,数组又可分为数值数组、字符数组、指针数组、结构数组等各种类别。   本章介绍数值数组和字符数组,其余的在以后各章陆续介绍。数组类型说明 在C语言中使用数组必须先进行类型说明。 数组说明的一般形 式为: 类型说明符 数组名 [常量表达式],……; 其中,类型说明符是任一种基本数据类型或构造数据类型。 数组名是用户定义的数组标识符。 方括号中的常量表达式表示数据元素的个数,也称为数组的长度。 例如: int a[10]; 说明整型数组a,有10个元素。 float b[10],c[20]; 说明实型数组b,有10个元素,实型数组c,有20个元素。 char ch[20]; 说明字符数组ch,有20个元素。 对于数组类型说明应注意以下几点: 1.数组的类型实际上是指数组元素的取值类型。对于同一个数组,其所有元素的数据类型都是相同的。 2.数组名的书写规则应符合标识符的书写规定。 3.数组名不能与其它变量名相同,例如: void main() { int a; float a[10]; …… } 是错误的。 4.方括号中常量表达式表示数组元素的个数,如a[5]表示数组a有5个元素。但是其下标从0开始计算。因此5个元素分别为a[0],a[1],a[2],a[3],a[4]。 5.不能在方括号中用变量来表示元素的个数, 但是可以是符号常数或常量表达式。例如: #define FD 5 void main() { int a[3+2],b[7+FD]; …… } 是合法的。但是下述说明方式是错误的。 void main() { int n=5; int a[n]; …… } 6.允许在同一个类型说明中,说明多个数组和多个变量。 例如: int a,b,c,d,k1[10],k2[20]; 数组元素的表示方法   数组元素是组成数组的基本单元。数组元素也是一种变量, 其标识方法为数组名后跟一个下标。 下标表示了元素在数组中的顺序号。数组元素的一般形式为: 数组名[下标] 其中的下标只能为整型常量或整型表达式。如为小数时,C编译将自动取整。例如,a[5],a[i+j],a[i++]都是合法的数组元素。 数组元素通常也称为下标变量。必须先定义数组, 才能使用下标变量。在C语言中只能逐个地使用下标变量, 而不能一次引用整个数组。 例如,输出有10 个元素的数组必须使用循环语句逐个输出各下标变量: for(i=0; i<10; i++)  printf("%d",a[i]); 而不能用一个语句输出整个数组,下面的写法是错误的: printf("%d",a); void main() { int i,a[10]; for(i=0;i<10;) a[i++]=2*i+1; for(i=9;i>=0;i--) printf("%d",a[i]); printf("\n%d %d\n",a[5.2],a[5.8]);} for(i=0;i<10;) a[i++]=2*i+1; for(i=9;i>=0;i--) printf("%d",a[i]); printf("\n%d %d\n",a[5.2],a[5.8]);   本例中用一个循环语句给a数组各元素送入奇数值,然后用第二个循环语句从大到小输出各个奇数。在第一个 for语句中,表达式3省略了。在下标变量中使用了表达式i++,用以修改循环变量。当然第二个for语句也可以这样作, C语言允许用表达式表示下标。 程序中最后一个printf语句输出了两次a[5]的值, 可以看出当下标不为整数时将自动取整。数组的赋值给数组赋值的方法除了用赋值语句对数组元素逐个赋值外, 还可采用初始化赋值和动态赋值的方法。数组初始化赋值数组初始化赋值是指在数组说明时给数组元素赋予初值。 数组初始化是在编译阶段进行的。这样将减少运行时间,提高效率。   初始化赋值的一般形式为: static 类型说明符 数组名[常量表达式]={值,值……值}; 其中static表示是静态存储类型, C语言规定只有静态存储数组和外部存储数组才可作初始化赋值(有关静态存储,外部存储的概念在第五章中介绍)。在{ }中的各数据值即为各元素的初值, 各值之间用逗号间隔。例如: static int a[10]={ 0,1,2,3,4,5,6,7,8,9 }; 相当于a[0]=0;a[1]=1...a[9]=9;   C语言对数组的初始赋值还有以下几点规定: 1.可以只给部分元素赋初值。当{ }中值的个数少于元素个数时,只给前面部分元素赋值。例如: static int a[10]={0,1,2,3,4};表示只给a[0]~a[4]5个元素赋值,而后5个元素自动赋0值。 2.只能给元素逐个赋值,不能给数组整体赋值。 例如给十个元素全部赋1值,只能写为: static int a[10]={1,1,1,1,1,1,1,1,1,1};而不能写为: static int a[10]=1; 3.如不给可初始化的数组赋初值,则全部元素均为0值。 4.如给全部元素赋值,则在数组说明中, 可以不给出数组元素的个数。例如: static int a[5]={1,2,3,4,5};可写为: static int a[]={1,2,3,4,5};动态赋值可以在程序执行过程中,对数组作动态赋值。 这时可用循环语句配合scanf函数逐个对数组元素赋值。 void main() { int i,max,a[10]; printf("input 10 numbers:\n"); for(i=0;i<10;i++) scanf("%d",&a[i]); max=a[0]; for(i=1;i<10;i++) if(a[i]>max) max=a[i]; printf("maxmum=%d\n",max); } for(i=0;i<10;i++) scanf("%d",&a[i]); max=a[0]; for(i=1;i<10;i++) if(a[i]>max) max=a[i]; printf("maxmum=%d\n",max);   本例程序中第一个for语句逐个输入10个数到数组a中。 然后把a[0]送入max中。在第二个for语句中,从a[1]到a[9]逐个与max中的内容比较,若比max的值大,则把该下标变量送入max中,因此max总是在已比较过的下标变量中为最大者。比较结束,输出max的值。 void main() { int i,j,p,q,s,a[10]; printf("\n input 10 numbers:\n"); for(i=0;i<10;i++) scanf("%d",&a[i]); for(i=0;i<10;i++){ p=i;q=a[i]; for(j=i+1;j<10;j++) if(q0) printf("st1>st2\n"); if(k<0) printf("st10) printf("st1>st2\n"); if(k<0) printf("st1st2”。 6.测字符串长度函数strlen 格式: strlen(字符数组名) 功能:测字符串的实际长度(不含字符串结束标志‘\0’) 并作为函数返回值。 #include"string.h" main() { int k; static char st[]="C language"; k=strlen(st); printf("The lenth of the string is %d\n",k); } 程序举例   把一个整数按大小顺序插入已排好序的数组中。 为了把一个数按大小插入已排好序的数组中, 应首先确定排序是从大到小还是从小到大进行的。设排序是从大到小进序的, 则可把欲插入的数与数组中各数逐个比较, 当找到第一个比插入数小的元素i时,该元素之前即为插入位置。然后从数组最后一个元素开始到该元素为止,逐个后移一个单元。最后把插入数赋予元素i即可。如果被插入数比所有的元素值都小则插入最后位置。 main() { int i,j,p,q,s,n,a[11]={127,3,6,28,54,68,87,105,162,18}; for(i=0;i<10;i++) { p=i;q=a[i]; for(j=i+1;j<10;j++) if(qa[i]) {for(s=9;s>=i;s--) a[s+1]=a[s]; break;} a[i]=n; for(i=0;i<=10;i++) printf("%d ",a[i]); printf("\n"); } scanf("%d",&n); for(i=0;i<10;i++) if(n>a[i]) { for(s=9;s>=i;s--) a[s+1]=a[s]; break; } a[i]=n; 本程序首先对数组a中的10个数从大到小排序并输出排序结果。然后输入要插入的整数n。再用一个for语句把n和数组元素逐个比较,如果发现有n>a[i]时,则由一个内循环把i以下各元素值顺次后移一个单元。后移应从后向前进行(从a[9]开始到a[i]为止)。 后移结束跳出外循环。插入点为i,把n赋予a[i]即可。 如所有的元素均大于被插入数,则并未进行过后移工作。此时i=10,结果是把n赋于a[10]。最后一个循环输出插入数后的数组各元素值。程序运行时,输入数47。从结果中可以看出47已插入到54和 28之间。   在二维数组a中选出各行最大的元素组成一个一维数组b。 a=3 16 87 65 4 32 11 108 10 25 12 37b=(87 108 37) 本题的编程思路是,在数组A的每一行中寻找最大的元素,找到之后把该值赋予数组B相应的元素即可。程序如下: main() { static int a[][4]={3,16,87,65,4,32,11,108,10,25,12,27}; int b[3],i,j,l; for(i=0;i<=2;i++) { l=a[i][0]; for(j=1;j<=3;j++) if(a[i][j]>l) l=a[i][j]; b[i]=l;} printf("\narray a:\n"); for(i=0;i<=2;i++) { for(j=0;j<=3;j++) printf("%5d",a[i][j]); printf("\n");} printf("\narray b:\n"); for(i=0;i<=2;i++) printf("%5d",b[i]); printf("\n"); } for(i=0;i<=2;i++){ l=a[i][0]; for(j=1;j<=3;j++) if(a[i][j]>l) l=a[i][j]; b[i]=l; }   程序中第一个for语句中又嵌套了一个for语句组成了双重循环。外循环控制逐行处理,并把每行的第0列元素赋予l。进入内循环后,把l与后面各列元素比较,并把比l大者赋予l。内循环结束时l 即为该行最大的元素,然后把l值赋予b[i]。等外循环全部完成时,数组b中已装入了a各行中的最大值。后面的两个 for语句分别输出数组a和数组b。   输入五个国家的名称按字母顺序排列输出。   本题编程思路如下:五个国家名应由一个二维字符数组来处理。然而C语言规定可以把一个二维数组当成多个一维数组处理。 因此本题又可以按五个一维数组处理, 而每一个一维数组就是一个国家名字符串。用字符串比较函数比较各一维数组的大小,并排序, 输出结果即可。 编程如下: void main() { char st[20],cs[5][20]; int i,j,p; printf("input country's name:\n"); for(i=0;i<5;i++) gets(cs[i]); printf("\n"); for(i=0;i<5;i++) { p=i;strcpy(st,cs[i]); for(j=i+1;j<5;j++) if(strcmp(cs[j],st)<0) {p=j;strcpy(st,cs[j]);} if(p!=i) { strcpy(st,cs[i]); strcpy(cs[i],cs[p]); strcpy(cs[p],st); } puts(cs[i]);}printf("\n"); } for(i=0;i<5;i++) { p=i;strcpy(st,cs[i]); for(j=i+1;j<5;j++) if(strcmp(cs[j],st)<0) { p=j;strcpy(st,cs[j]);} if(p!=i) { strcpy(st,cs[i]); strcpy(cs[i],cs[p]); strcpy(cs[p],st); }   本程序的第一个for语句中,用gets函数输入五个国家名字符串。上面说过C语言允许把一个二维数组按多个一维数组处理, 本程序说明cs[5][20]为二维字符数组,可分为五个一维数组cs[0],cs[1],cs[2],cs[3],cs[4]。因此在gets函数中使用cs[i]是合法的。 在第二个for语句中又嵌套了一个for语句组成双重循环。 这个双重循环完成按字母顺序排序的工作。在外层循环中把字符数组cs[i]中的国名字符串拷贝到数组st中,并把下标i赋予P。 进入内层循环后,把st与cs[i]以后的各字符串作比较,若有比st小者则把该字符串拷贝到st中,并把其下标赋予p。内循环完成后如p不等于 i 说明有比cs[i]更小的字符串出现,因此交换cs[i]和st的内容。 至此已确定了数组cs的第i号元素的排序值。然后输出该字符串。在外循环全部完成之后即完成全部排序和输出。 本章小结 1.数组是程序设计中最常用的数据结构。数组可分为数值数组(整数组,实数组),字符数组以及后面将要介绍的指针数组,结构数组等。 2.数组可以是一维的,二维的或多维的。 3.数组类型说明由类型说明符、数组名、数组长度 (数组元素个数)三部分组成。数组元素又称为下标变量。 数组的类型是指下标变量取值的类型。 4.对数组的赋值可以用数组初始化赋值, 输入函数动态赋值和赋值语句赋值三种方法实现。 对数值数组不能用赋值语句整体赋值、输入或输出,而必须用循环语句逐个对数组元素进行操作。 第五章:函数 概述   在第一章中已经介绍过,C源程序是由函数组成的。 虽然在前面各章的程序中都只有一个主函数main(), 但实用程序往往由多个函数组成。函数是C源程序的基本模块, 通过对函数模块的调用实现特定的功能。C语言中的函数相当于其它高级语言的子程序。 C语言不仅提供了极为丰富的库函数(如Turbo C,MS C 都提供了三百多个库函数),还允许用户建立自己定义的函数。用户可把自己的算法编成一个个相对独立的函数模块,然后用调用的方法来使用函数。   可以说C程序的全部工作都是由各式各样的函数完成的, 所以也把C语言称为函数式语言。 由于采用了函数模块式的结构, C语言易于实现结构化程序设计。使程序的层次结构清晰,便于程序的编写、阅读、调试。   在C语言中可从不同的角度对函数分类。 1. 从函数定义的角度看,函数可分为库函数和用户定义函数两种。 (1)库函数   由C系统提供,用户无须定义, 也不必在程序中作类型说明,只需在程序前包含有该函数原型的头文件即可在程序中直接调用。在前面各章的例题中反复用到printf 、 scanf 、 getchar 、putchar、gets、puts、strcat等函数均属此类。 (2)用户定义函数   由用户按需要写的函数。对于用户自定义函数, 不仅要在程序中定义函数本身, 而且在主调函数模块中还必须对该被调函数进行类型说明,然后才能使用。 2. C语言的函数兼有其它语言中的函数和过程两种功能,从这个角度看,又可把函数分为有返回值函数和无返回值函数两种。 (1)有返回值函数   此类函数被调用执行完后将向调用者返回一个执行结果, 称为函数返回值。如数学函数即属于此类函数。 由用户定义的这种要返回函数值的函数,必须在函数定义和函数说明中明确返回值的类型。 (2)无返回值函数   此类函数用于完成某项特定的处理任务, 执行完成后不向调用者返回函数值。这类函数类似于其它语言的过程。 由于函数无须返回值,用户在定义此类函数时可指定它的返回为“空类型”, 空类型的说明符为“void”。 3. 从主调函数和被调函数之间数据传送的角度看又可分为无参函数和有参函数两种。 (1)无参函数   函数定义、函数说明及函数调用中均不带参数。 主调函数和被调函数之间不进行参数传送。 此类函数通常用来完成一组指定的功能,可以返回或不返回函数值。 (2)有参函数   也称为带参函数。在函数定义及函数说明时都有参数, 称为形式参数(简称为形参)。在函数调用时也必须给出参数, 称为实际参数(简称为实参)。 进行函数调用时,主调函数将把实参的值传送给形参,供被调函数使用。 4. C语言提供了极为丰富的库函数, 这些库函数又可从功能角度作以下分类。 (1)字符类型分类函数   用于对字符按ASCII码分类:字母,数字,控制字符,分隔符,大小写字母等。 (2)转换函数   用于字符或字符串的转换;在字符量和各类数字量 (整型, 实型等)之间进行转换;在大、小写之间进行转换。 (3)目录路径函数   用于文件目录和路径操作。 (4)诊断函数   用于内部错误检测。 (5)图形函数   用于屏幕管理和各种图形功能。 (6)输入输出函数   用于完成输入输出功能。 (7)接口函数   用于与DOS,BIOS和硬件的接口。 (8)字符串函数   用于字符串操作和处理。 (9)内存管理函数   用于内存管理。 (10)数学函数   用于数学函数计算。 (11)日期和时间函数   用于日期,时间转换操作。 (12)进程控制函数   用于进程管理和控制。 (13)其它函数   用于其它各种功能。      以上各类函数不仅数量多,而且有的还需要硬件知识才会使用,因此要想全部掌握则需要一个较长的学习过程。 应首先掌握一些最基本、 最常用的函数,再逐步深入。由于篇幅关系,本书只介绍了很少一部分库函数, 其余部分读者可根据需要查阅有关手册。   还应该指出的是,在C语言中,所有的函数定义,包括主函数main在内,都是平行的。也就是说,在一个函数的函数体内, 不能再定义另一个函数, 即不能嵌套定义。但是函数之间允许相互调用,也允许嵌套调用。习惯上把调用者称为主调函数。 函数还可以自己调用自己,称为递归调用。main 函数是主函数,它可以调用其它函数,而不允许被其它函数调用。 因此,C程序的执行总是从main函数开始, 完成对其它函数的调用后再返回到main函数,最后由main函数结束整个程序。一个C源程序必须有,也只能有一个主函数main。    函数定义的一般形式 1.无参函数的一般形式 类型说明符 函数名() { 类型说明 语句 }   其中类型说明符和函数名称为函数头。 类型说明符指明了本函数的类型,函数的类型实际上是函数返回值的类型。 该类型说明符与第二章介绍的各种说明符相同。 函数名是由用户定义的标识符,函数名后有一个空括号,其中无参数,但括号不可少。{} 中的内容称为函数体。在函数体中也有类型说明, 这是对函数体内部所用到的变量的类型说明。在很多情况下都不要求无参函数有返回值, 此时函数类型符可以写为void。 我们可以改为一个函数定义: void Hello() { printf ("Hello,world \n"); }  这里,只把main改为Hello作为函数名,其余不变。Hello 函数是一个无参函数,当被其它函数调用时,输出Hello world字符串。 2.有参函数的一般形式 类型说明符 函数名(形式参数表) 型式参数类型说明 { 类型说明 语句 }   有参函数比无参函数多了两个内容,其一是形式参数表, 其二是形式参数类型说明。在形参表中给出的参数称为形式参数, 它们可以是各种类型的变量, 各参数之间用逗号间隔。在进行函数调用时,主调函数将赋予这些形式参数实际的值。 形参既然是变量,当然必须给以类型说明。例如,定义一个函数, 用于求两个数中的大数,可写为: int max(a,b) int a,b; { if (a>b) return a; else return b; }   第一行说明max函数是一个整型函数,其返回的函数值是一个整数。形参为a,b。第二行说明a,b均为整型量。 a,b 的具体值是由主调函数在调用时传送过来的。在{}中的函数体内, 除形参外没有使用其它变量,因此只有语句而没有变量类型说明。 上边这种定义方法称为“传统格式”。 这种格式不易于编译系统检查,从而会引起一些非常细微而且难于跟踪的错误。ANSI C 的新标准中把对形参的类型说明合并到形参表中,称为“现代格式”。   例如max函数用现代格式可定义为: int max(int a,int b) { if(a>b) return a; else return b; }   现代格式在函数定义和函数说明(后面将要介绍)时, 给出了形式参数及其类型,在编译时易于对它们进行查错, 从而保证了函数说明和定义的一致性。例1.3即采用了这种现代格式。 在max函数体中的return语句是把a(或b)的值作为函数的值返回给主调函数。有返回值函数中至少应有一个return语句。 在C程序中,一个函数的定义可以放在任意位置, 既可放在主函数main之前,也可放在main之后。例如例1.3中定义了一个max 函数,其位置在main之后, 也可以把它放在main之前。 修改后的程序如下所示。 int max(int a,int b) { if(a>b)return a; else return b; } void main() { int max(int a,int b); int x,y,z; printf("input two numbers:\n"); scanf("%d%d",&x,&y); z=max(x,y); printf("maxmum=%d",z); }   现在我们可以从函数定义、 函数说明及函数调用的角度来分析整个程序,从中进一步了解函数的各种特点。程序的第1行至第5行为max函数定义。进入主函数后,因为准备调用max函数,故先对max函数进行说明(程序第8行)。函数定义和函数说明并不是一回事,在后面还要专门讨论。 可以看出函数说明与函数定义中的函数头部分相同,但是末尾要加分号。程序第12 行为调用max函数,并把x,y中的值传送给max的形参a,b。max函数执行的 结果 (a或b)将返回给变量z。最后由主函数输出z的值。   函数调用的一般形式前面已经说过,在程序中是通过对函数的调用来执行函数体的,其过程与其它语言的子程序调用相似。C语言中, 函数调用的一般形式为:   函数名(实际参数表) 对无参函数调用时则无实际参数表。 实际参数表中的参数可以是常数,变量或其它构造类型数据及表达式。 各实参之间用逗号分隔。'Next of Page在C语言中,可以用以下几种方式调用函数: 1.函数表达式   函数作表达式中的一项出现在表达式中,以函数返回值参与表达式的运算。这种方式要求函数是有返回值的。例如: z=max(x,y)是一个赋值表达式,把max的返回值赋予变量z。'Next of Page 2.函数语句   函数调用的一般形式加上分号即构成函数语句。例如: printf ("%D",a);scanf ("%d",&b);都是以函数语句的方式调用函数。 3.函数实参   函数作为另一个函数调用的实际参数出现。 这种情况是把该函数的返回值作为实参进行传送,因此要求该函数必须是有返回值的。例如: printf("%d",max(x,y)); 即是把max调用的返回值又作为printf函数的实参来使用的。在函数调用中还应该注意的一个问题是求值顺序的问题。 所谓求值顺序是指对实参表中各量是自左至右使用呢,还是自右至左使用。 对此, 各系统的规定不一定相同。在3.1.3节介绍printf 函数时已提 到过,这里从函数调用的角度再强调一下。 看例5.2程序。 void main() { int i=8; printf("%d\n%d\n%d\n%d\n",++i,--i,i++,i--); } 如按照从右至左的顺序求值。例5.2的运行结果应为: 8 7 7 8 如对printf语句中的++i,--i,i++,i--从左至右求值,结果应为: 9 8 8 9   应特别注意的是,无论是从左至右求值, 还是自右至左求值,其输出顺序都是不变的, 即输出顺序总是和实参表中实参的顺序相同。由于Turbo C现定是自右至左求值,所以结果为8,7,7,8。上述问题如还不理解,上机一试就明白了。函数的参数和函数的值 一、函数的参数   前面已经介绍过,函数的参数分为形参和实参两种。 在本小节中,进一步介绍形参、实参的特点和两者的关系。 形参出现在函数定义中,在整个函数体内都可以使用, 离开该函数则不能使用。实参出现在主调函数中,进入被调函数后,实参变量也不能使用。 形参和实参的功能是作数据传送。发生函数调用时, 主调函数把实参的值传送给被调函数的形参从而实现主调函数向被调函数的数据传送。   函数的形参和实参具有以下特点: 1.形参变量只有在被调用时才分配内存单元,在调用结束时, 即刻释放所分配的内存单元。因此,形参只有在函数内部有效。 函数调用结束返回主调函数后则不能再使用该形参变量。 2.实参可以是常量、变量、表达式、函数等, 无论实参是何种类型的量,在进行函数调用时,它们都必须具有确定的值, 以便把这些值传送给形参。 因此应预先用赋值,输入等办法使实参获得确定值。 3.实参和形参在数量上,类型上,顺序上应严格一致, 否则会发生“类型不匹配”的错误。 4.函数调用中发生的数据传送是单向的。 即只能把实参的值传送给形参,而不能把形参的值反向地传送给实参。 因此在函数调用过程中,形参的值发生改变,而实参中的值不会变化。例5.3可以说明这个问题。 void main() { int n; printf("input number\n"); scanf("%d",&n); s(n); printf("n=%d\n",n); } int s(int n) { int i; for(i=n-1;i>=1;i--) n=n+i; printf("n=%d\n",n); } 本程序中定义了一个函数s,该函数的功能是求∑ni=1i 的值。在主函数中输入n值,并作为实参,在调用时传送给s 函数的形参量n( 注意,本例的形参变量和实参变量的标识符都为n, 但这是两个不同的量,各自的作用域不同)。 在主函数中用printf 语句输出一次n值,这个n值是实参n的值。在函数s中也用printf 语句输出了一次n值,这个n值是形参最后取得的n值0。从运行情况看,输入n值为100。即实参n的值为100。把此值传给函数s时,形参 n 的初值也为100,在执行函数过程中,形参n的值变为5050。 返回主函数之后,输出实参n的值仍为100。可见实参的值不随形参的变化而变化。 二、函数的值   函数的值是指函数被调用之后, 执行函数体中的程序段所取得的并返回给主调函数的值。如调用正弦函数取得正弦值,调用例5.1的max函数取得的最大数等。对函数的值(或称函数返回值)有以下一些说明: 1. 函数的值只能通过return语句返回主调函数。return 语句的一般形式为: return 表达式; 或者为: return (表达式); 该语句的功能是计算表达式的值,并返回给主调函数。 在函数中允许有多个return语句,但每次调用只能有一个return 语句被执行, 因此只能返回一个函数值。 2. 函数值的类型和函数定义中函数的类型应保持一致。 如果两者不一致,则以函数类型为准,自动进行类型转换。 3. 如函数值为整型,在函数定义时可以省去类型说明。 4. 不返回函数值的函数,可以明确定义为“空类型”, 类型说明符为“void”。如例5.3中函数s并不向主函数返函数值,因此可定义为: void s(int n) { …… }   一旦函数被定义为空类型后, 就不能在主调函数中使用被调函数的函数值了。例如,在定义s为空类型后,在主函数中写下述语句 sum=s(n); 就是错误的。为了使程序有良好的可读性并减少出错, 凡不要求返回值的函数都应定义为空类型。函数说明在主调函数中调用某函数之前应对该被调函数进行说明, 这与使用变量之前要先进行变量说明是一样的。 在主调函数中对被调函数作说明的目的是使编译系统知道被调函数返回值的类型, 以便在主调函数中按此种类型对返回值作相应的处理。 对被调函数的说明也有两种格式,一种为传统格式,其一般格式为: 类型说明符 被调函数名(); 这种格式只给出函数返回值的类型,被调函数名及一个空括号。   这种格式由于在括号中没有任何参数信息, 因此不便于编译系统进行错误检查,易于发生错误。另一种为现代格式,其一般形式为: 类型说明符 被调函数名(类型 形参,类型 形参…); 或为: 类型说明符 被调函数名(类型,类型…);   现代格式的括号内给出了形参的类型和形参名, 或只给出形参类型。这便于编译系统进行检错,以防止可能出现的错误。例5.1 main函数中对max函数的说明若 用传统格式可写为: int max(); 用现代格式可写为: int max(int a,int b); 或写为: int max(int,int);   C语言中又规定在以下几种情况时可以省去主调函数中对被调函数的函数说明。 1. 如果被调函数的返回值是整型或字符型时, 可以不对被调函数作说明,而直接调用。这时系统将自动对被调函数返回值按整型处理。例5.3的主函数中未对函数s作说明而直接调用即属此种情形。 2. 当被调函数的函数定义出现在主调函数之前时, 在主调函数中也可以不对被调函数再作说明而直接调用。例如例5.1中, 函数max的定义放在main 函数之前,因此可在main函数中省去对 max函数的函数说明int max(int a,int b)。 3. 如在所有函数定义之前, 在函数外预先说明了各个函数的类型,则在以后的各主调函数中,可不再对被调函数作说明。例如: char str(int a); float f(float b); main() { …… } char str(int a) { …… } float f(float b) { …… } 其中第一,二行对str函数和f函数预先作了说明。 因此在以后各函数中无须对str和f函数再作说明就可直接调用。 4. 对库函数的调用不需要再作说明, 但必须把该函数的头文件用include命令包含在源文件前部。数组作为函数参数数组可以作为函数的参数使用,进行数据传送。 数组用作函数参数有两种形式,一种是把数组元素(下标变量)作为实参使用; 另一种是把数组名作为函数的形参和实参使用。一、数组元素作函数实参数组元素就是下标变量,它与普通变量并无区别。 因此它作为函数实参使用与普通变量是完全相同的,在发生函数调用时, 把作为实参的数组元素的值传送给形参,实现单向的值传送。例5.4说明了这种情况。[例5.4]判别一个整数数组中各元素的值,若大于0 则输出该值,若小于等于0则输出0值。编程如下: void nzp(int v) { if(v>0) printf("%d ",v); else printf("%d ",0); } main() { int a[5],i; printf("input 5 numbers\n"); for(i=0;i<5;i++) { scanf("%d",&a[i]); nzp(a[i]); } }void nzp(int v) { …… } main() { int a[5],i; printf("input 5 numbers\n"); for(i=0;i<5;i++) { scanf("%d",&a[i]); nzp(a[i]); } }   本程序中首先定义一个无返回值函数nzp,并说明其形参v 为整型变量。在函数体中根据v值输出相应的结果。在main函数中用一个for 语句输入数组各元素, 每输入一个就以该元素作实参调用一次nzp函数,即把a[i]的值传送给形参v,供nzp函数使用。 二、数组名作为函数参数   用数组名作函数参数与用数组元素作实参有几点不同: 1. 用数组元素作实参时,只要数组类型和函数的形参变量的类型一致,那么作为下标变量的数组元素的类型也和函数形参变量的类型是一致的。因此, 并不要求函数的形参也是下标变量。 换句话说,对数组元素的处理是按普通变量对待的。用数组名作函数参数时, 则要求形参和相对应的实参都必须是类型相同的数组,都必须有明确的数组说明。当形参和实参二者不一致时,即会发生错误。 2. 在普通变量或下标变量作函数参数时,形参变量和实参变量是由编译系统分配的两个不同的内存单元。在函数调用时发生的值传送是把实参变量的值赋予形参变量。在用数组名作函数参数时,不是进行值的传送,即不是把实参数组的每一个元素的值都赋予形参数组的各个元素。因为实际上形参数组并不存在,编译系统不为形参数组分配内存。那么,数据的传送是如何实现的呢? 在第四章中我们曾介绍过,数组名就是数组的首地址。因此在数组名作函数参数时所进行的传送只是地址的传送, 也就是说把实参数组的首地址赋予形参数组名。形参数组名取得该首地址之后,也就等于有了实在的数组。实际上是形参数组和实参数组为同一数组,共同拥有一段内存空间。图5.1说明了这种情形。图中设a为实参数组,类型为整型。a占有以2000 为首地址的一块内存区。b为形参数组名。当发生函数调用时,进行地址传送, 把实参数 组a的首地址传送给形参数组名b,于是b也取得该地址2000。 于是a,b两数组共同占有以2000 为首地址的一段连续内存单元。从图中还可以看出a和b下标相同的元素实际上也占相同的两个内 存单元(整型数组每个元素占二字节)。例如a[0]和b[0]都占用2000和2001单元,当然a[0]等于b[0]。类推则有a[i]等于b[i]。 [例5.5]数组a中存放了一个学生5门课程的成绩,求平均成绩。float aver(float a[5]) { int i; float av,s=a[0]; for(i=1;i<5;i++) s=s+a[i]; av=s/5; return av; } void main() { float sco[5],av; int i; printf("\ninput 5 scores:\n"); for(i=0;i<5;i++) scanf("%f",&sco[i]); av=aver(sco); printf("average score is %5.2f",av); } float aver(float a[5]) { …… } void main() { …… for(i=0;i<5;i++) scanf("%f",&sco[i]); av=aver(sco); …… }   本程序首先定义了一个实型函数aver,有一个形参为实型数组a,长度为5。在函数aver中,把各元素值相加求出平均值,返回给主函数。主函数main 中首先完成数组sco的输入,然后以sco作为实参调用aver函数,函数返回值送av,最后输出av值。 从运行情况可以看出,程序实现了所要求的功能 3. 前面已经讨论过,在变量作函数参数时,所进行的值传送是单向的。即只能从实参传向形参,不能从形参传回实参。形参的初值和实参相同, 而形参的值发生改变后,实参并不变化, 两者的终值是不同的。例5.3证实了这个结论。 而当用数组名作函数参数时,情况则不同。 由于实际上形参和实参为同一数组, 因此当形参数组发生变化时,实参数组也随之变化。 当然这种情况不能理解为发生了“双向”的值传递。但从实际情况来看,调用函数之后实参数组的值将由于形参数组值的变化而变化。为了说明这种情况,把例5.4改为例5.6的形式。[例5.6]题目同5.4例。改用数组名作函数参数。 void nzp(int a[5]) { int i; printf("\nvalues of array a are:\n"); for(i=0;i<5;i++) { if(a[i]<0) a[i]=0; printf("%d ",a[i]); } } main() { int b[5],i; printf("\ninput 5 numbers:\n"); for(i=0;i<5;i++) scanf("%d",&b[i]); printf("initial values of array b are:\n"); for(i=0;i<5;i++) printf("%d ",b[i]); nzp(b); printf("\nlast values of array b are:\n"); for(i=0;i<5;i++) printf("%d ",b[i]); } void nzp(int a[5]) { …… } main() { int b[5],i; …… nzp(b); …… }   本程序中函数nzp的形参为整数组a,长度为 5。 主函数中实参数组b也为整型,长度也为5。在主函数中首先输入数组b的值,然后输出数组b的初始值。 然后以数组名b为实参调用nzp函数。在nzp中,按要求把负值单元清0,并输出形参数组a的值。 返回主函数之后,再次输出数组b的值。从运行结果可以看出,数组b 的初值和终值是不同的,数组b 的终值和数组a是相同的。这说明实参形参为同一数组,它们的值同时得以改变。 用数组名作为函数参数时还应注意以下几点: a. 形参数组和实参数组的类型必须一致,否则将引起错误。 b. 形参数组和实参数组的长度可以不相同,因为在调用时,只传送首地址而不检查形参数组的长度。当形参数组的长度与实参数组不一致时,虽不至于出现语法错误(编译能通过),但程序执行结果将与实际不符,这是应予以注意的。如把例5.6修改如下: void nzp(int a[8]) { int i; printf("\nvalues of array aare:\n"); for(i=0;i<8;i++) { if(a[i]<0)a[i]=0; printf("%d",a[i]); } } main() { int b[5],i; printf("\ninput 5 numbers:\n"); for(i=0;i<5;i++) scanf("%d",&b[i]); printf("initial values of array b are:\n"); for(i=0;i<5;i++) printf("%d",b[i]); nzp(b); printf("\nlast values of array b are:\n"); for(i=0;i<5;i++) printf("%d",b[i]); }   本程序与例5.6程序比,nzp函数的形参数组长度改为8,函数体中,for语句的循环条件也改为i<8。因此,形参数组 a和实参数组b的长度不一致。编译能够通过,但从结果看,数组a的元素a[5],a[6],a[7]显然是无意义的。c. 在函数形参表中,允许不给出形参数组的长度,或用一个变量来表示数组元素的个数。 例如:可以写为: void nzp(int a[]) 或写为 void nzp(int a[],int n)   其中形参数组a没有给出长度,而由n值动态地表示数组的长度。n的值由主调函数的实参进行传送。 由此,例5.6又可改为例5.7的形式。 [例5.7]void nzp(int a[],int n) { int i; printf("\nvalues of array a are:\n"); for(i=0;i1) 按公式可编程如下: long ff(int n) { long f; if(n<0) printf("n<0,input error"); else if(n==0||n==1) f=1; else f=ff(n-1)*n; return(f); } main() { int n; long y; printf("\ninput a inteager number:\n"); scanf("%d",&n); y=ff(n); printf("%d!=%ld",n,y); } long ff(int n) { …… else f=ff(n-1)*n; …… } main() { …… y=ff(n); …… }   程序中给出的函数ff是一个递归函数。主函数调用ff 后即进入函数ff执行,如果n<0,n==0或n=1时都将结束函数的执行,否则就递归调用ff函数自身。由于每次递归调用的实参为n-1,即把n-1 的值赋予形参n,最后当n-1的值为1时再作递归调用,形参n的值也为1,将使递归终止。然后可逐层退回。下面我们再举例说明该过程。 设执行本程序时输入为5, 即求 5!。在主函数中的调用语句即为y=ff(5),进入ff函数后,由于n=5,不等于0或1,故应执行f=ff(n-1)*n,即f=ff(5-1)*5。该语句对ff作递归调用即ff(4)。 逐次递归展开如图5.3所示。进行四次递归调用后,ff函数形参取得的值变为1,故不再继续递归调用而开始逐层返回主调函数。ff(1)的函数返回值为1,ff(2)的返回值为1*2=2,ff(3)的返回值为2*3=6,ff(4) 的返 回值为6*4=24,最后返回值ff(5)为24*5=120。   例5. 9也可以不用递归的方法来完成。如可以用递推法,即从1开始乘以2,再乘以3…直到n。递推法比递归法更容易理解和实现。但是有些问题则只能用递归算法才能实现。典型的问题是Hanoi塔问题。      [例5.10]Hanoi塔问题 一块板上有三根针,A,B,C。A针上套有64个大小不等的圆盘, 大的在下,小的在上。如图5.4所示。要把这64个圆盘从A针移动C针上,每次只能移动一个圆盘,移动可以借助B针进行。但在任何时候,任何针上的圆盘都必须保持大盘在下,小盘在上。求移动的步骤。 本题算法分析如下,设A上有n个盘子。 如果n=1,则将圆盘从A直接移动到C。 如果n=2,则: 1.将A上的n-1(等于1)个圆盘移到B上; 2.再将A上的一个圆盘移到C上; 3.最后将B上的n-1(等于1)个圆盘移到C上。 如果n=3,则: A. 将A上的n-1(等于2,令其为n`)个圆盘移到B(借助于C), 步骤如下: (1)将A上的n`-1(等于1)个圆盘移到C上,见图5.5(b)。 (2)将A上的一个圆盘移到B,见图5.5(c) (3)将C上的n`-1(等于1)个圆盘移到B,见图5.5(d) B. 将A上的一个圆盘移到C,见图5.5(e) C. 将B上的n-1(等于2,令其为n`)个圆盘移到C(借助A), 步骤如下: (1)将B上的n`-1(等于1)个圆盘移到A,见图5.5(f) (2)将B上的一个盘子移到C,见图5.5(g) (3)将A上的n`-1(等于1)个圆盘移到C,见图5.5(h)。 到此,完成了三个圆盘的移动过程。 从上面分析可以看出,当n大于等于2时, 移动的过程可分解为 三个步骤: 第一步 把A上的n-1个圆盘移到B上; 第二步 把A上的一个圆盘移到C上; 第三步 把B上的n-1个圆盘移到C上;其中第一步和第三步是类同的。 当n=3时,第一步和第三步又分解为类同的三步,即把n`-1个圆盘从一个针移到另一个针上,这里的n`=n-1。 显然这是一个递归过 程,据此算法可编程如下: move(int n,int x,int y,int z) { if(n==1) printf("%c-->%c\n",x,z); else { move(n-1,x,z,y); printf("%c-->%c\n",x,z); move(n-1,y,x,z); } } main() { int h; printf("\ninput number:\n"); scanf("%d",&h); printf("the step to moving %2d diskes:\n",h); move(h,'a','b','c'); } move(int n,int x,int y,int z) { if(n==1) printf("%-->%c\n",x,z); else { move(n-1,x,z,y); printf("%c-->%c\n",x,z); move(n-1,y,x,z); } } main() { …… move(h,'a','b','c'); }   从程序中可以看出,move函数是一个递归函数,它有四个形参n,x,y,z。n表示圆盘数,x,y,z分别表示三根针。move 函数的功能是把x上的n个圆盘移动到z 上。当n==1时,直接把x上的圆盘移至z上,输出x→z。如n!=1则分为三步:递归调用move函数,把n-1个圆盘从x移到y;输出x→z;递归调用move函数,把n-1个圆盘从y移到z。在递归调用过程中n=n-1,故n的值逐次递减,最后n=1时,终止递归,逐层返回。当n=4 时程序运行的结果为 input number: 4 the step to moving 4 diskes: a→b a→c b→c a→b c→a c→b a→b a→c b→c b→a c→a b→c a→b a→c b→c 变量的作用域   在讨论函数的形参变量时曾经提到, 形参变量只在被调用期间才分配内存单元,调用结束立即释放。 这一点表明形参变量只有在函数内才是有效的, 离开该函数就不能再使用了。这种变量有效性的范围称变量的作用域。不仅对于形参变量, C语言中所有的量都有自己的作用域。变量说明的方式不同,其作用域也不同。 C语言中的变量,按作用域范围可分为两种, 即局部变量和全局变量。 一、局部变量   局部变量也称为内部变量。局部变量是在函数内作定义说明的。其作用域仅限于函数内, 离开该函数后再使用这种变量是非法的。 例如: int f1(int a) /*函数f1*/ { int b,c; …… }a,b,c作用域 int f2(int x) /*函数f2*/ { int y,z; }x,y,z作用域 main() { int m,n; } m,n作用域 在函数f1内定义了三个变量,a为形参,b,c为一般变量。在 f1的范围内a,b,c有效,或者说a,b,c变量的作用域限于f1内。同理,x,y,z的作用域限于f2内。 m,n的作用域限于main函数内。关于局部变量的作用域还要说明以下几点: 1. 主函数中定义的变量也只能在主函数中使用,不能在其它函数中使用。同时,主函数中也不能使用其它函数中定义的变量。因为主函数也是一个函数,它与其它函数是平行关系。这一点是与其它语言不同的,应予以注意。 2. 形参变量是属于被调函数的局部变量,实参变量是属于主调函数的局部变量。 3. 允许在不同的函数中使用相同的变量名,它们代表不同的对象,分配不同的单元,互不干扰,也不会发生混淆。如在例5.3 中,形参和实参的变量名都为n,是完全允许的。4. 在复合语句中也可定义变量,其作用域只在复合语句范围内。例如: main() { int s,a; …… { int b; s=a+b; ……b作用域 } ……s,a作用域 }[例5.11]main() { int i=2,j=3,k; k=i+j; { int k=8; if(i==3) printf("%d\n",k); } printf("%d\n%d\n",i,k); } main() { int i=2,j=3,k; k=i+j; { int k=8; if(i=3) printf("%d\n",k); } printf("%d\n%d\n",i,k); }   本程序在main中定义了i,j,k三个变量,其中k未赋初值。 而在复合语句内又定义了一个变量k,并赋初值为8。应该注意这两个k不是同一个变量。在复合语句外由main定义的k起作用,而在复合语句内则由在复合语句内定义的k起作用。因此程序第4行的k为main所定义,其值应为5。第7行输出k值,该行在复合语句内,由复合语句内定义的k起作用,其初值为8,故输出值为8,第9行输出i,k值。i是在整个程序中有效的,第7行对i赋值为3,故以输出也为3。而第9行已在复合语句之外,输出的k应为main所定义的k,此k值由第4 行已获得为5,故输出也为5。 二、全局变量 全局变量也称为外部变量,它是在函数外部定义的变量。 它不属于哪一个函数,它属于一个源程序文件。其作用域是整个源程序。在函数中使用全局变量,一般应作全局变量说明。 只有在函数内经过说明的全局变量才能使用。全局变量的说明符为extern。 但在一个函数之前定义的全局变量,在该函数内使用可不再加以说明。 例如: int a,b; /*外部变量*/ void f1() /*函数f1*/ { …… } float x,y; /*外部变量*/ int fz() /*函数fz*/ { …… } main() /*主函数*/ { …… }/*全局变量x,y作用域 全局变量a,b作用域*/   从上例可以看出a、b、x、y 都是在函数外部定义的外部变量,都是全局变量。但x,y 定义在函数f1之后,而在f1内又无对x,y的说明,所以它们在f1内无效。 a,b定义在源程序最前面,因此在f1,f2及main内不加说明也可使用。 [例5.12]输入正方体的长宽高l,w,h。求体积及三个面x*y,x*z,y*z的面积。 int s1,s2,s3; int vs( int a,int b,int c) { int v; v=a*b*c; s1=a*b; s2=b*c; s3=a*c; return v; } main() { int v,l,w,h; printf("\ninput length,width and height\n"); scanf("%d%d%d",&l,&w,&h); v=vs(l,w,h); printf("v=%d s1=%d s2=%d s3=%d\n",v,s1,s2,s3); }   本程序中定义了三个外部变量s1,s2,s3, 用来存放三个面积,其作用域为整个程序。函数vs用来求正方体体积和三个面积, 函数的返回值为体积v。由主函数完成长宽高的输入及结果输出。由于C语言规定函数返回值只有一个, 当需要增加函数的返回数据时,用外部变量是一种很好的方式。本例中,如不使用外部变量, 在主函数中就不可能取得v,s1,s2,s3四个值。而采用了外部变量, 在函数vs中求得的s1,s2,s3值在main 中仍然有效。因此外部变量是实现函数之间数据通讯的有效手段。对于全局变量还有以下几点说明: 1. 对于局部变量的定义和说明,可以不加区分。而对于外部变量则不然,外部变量的定义和外部变量的说明并不是一回事。外部变量定义必须在所有的函数之外,且只能定义一次。其一般形式为: [extern] 类型说明符 变量名,变量名… 其中方括号内的extern可以省去不写。 例如: int a,b; 等效于: extern int a,b;   而外部变量说明出现在要使用该外部变量的各个函数内, 在整个程序内,可能出现多次,外部变量说明的一般形式为: extern 类型说明符 变量名,变量名,…; 外部变量在定义时就已分配了内存单元, 外部变量定义可作初始赋值,外部变量说明不能再赋初始值, 只是表明在函数内要使用某外部变量。 2. 外部变量可加强函数模块之间的数据联系, 但是又使函数要依赖这些变量,因而使得函数的独立性降低。从模块化程序设计的观点来看这是不利的, 因此在不必要时尽量不要使用全局变量。 3. 在同一源文件中,允许全局变量和局部变量同名。在局部变量的作用域内,全局变量不起作用。 [例5.13]int vs(int l,int w) { extern int h; int v; v=l*w*h; return v; } main() { extern int w,h; int l=5; printf("v=%d",vs(l,w)); } int l=3,w=4,h=5;   本例程序中,外部变量在最后定义, 因此在前面函数中对要用的外部变量必须进行说明。外部变量l,w和vs函数的形参l,w同名。外部变量都作了初始赋值,mian函数中也对l作了初始化赋值。执行程序时,在printf语句中调用vs函数,实参l的值应为main中定义的l值,等于5,外部变量l在main内不起作用;实参w的值为外部变量w的值为4,进入vs后这两个值传送给形参l,wvs函数中使用的h 为外部变量,其值为5,因此v的计算结果为100,返回主函数后输出。变量的存储类型各种变量的作用域不同, 就其本质来说是因变量的存储类型相同。所谓存储类型是指变量占用内存空间的方式, 也称为存储方式。 变量的存储方式可分为“静态存储”和“动态存储”两种。   静态存储变量通常是在变量定义时就分定存储单元并一直保持不变, 直至整个程序结束。5.5.1节中介绍的全局变量即属于此类存储方式。动态存储变量是在程序执行过程中,使用它时才分配存储单元, 使用完毕立即释放。 典型的例子是函数的形式参数,在函数定义时并不给形参分配存储单元,只是在函数被调用时,才予以分配, 调用函数完毕立即释放。如果一个函数被多次调用,则反复地分配、 释放形参变量的存储单元。从以上分析可知, 静态存储变量是一直存在的, 而动态存储变量则时而存在时而消失。我们又把这种由于变量存储方式不同而产生的特性称变量的生存期。 生存期表示了变量存在的时间。 生存期和作用域是从时间和空间这两个不同的角度来描述变量的特性,这两者既有联系,又有区别。 一个变量究竟属于哪一种存储方式, 并不能仅从其作用域来判断,还应有明确的存储类型说明。   在C语言中,对变量的存储类型说明有以下四种: auto     自动变量 register   寄存器变量 extern    外部变量 static    静态变量   自动变量和寄存器变量属于动态存储方式, 外部变量和静态变量属于静态存储方式。在介绍了变量的存储类型之后, 可以知道对一个变量的说明不仅应说明其数据类型,还应说明其存储类型。 因此变量说明的完整形式应为: 存储类型说明符 数据类型说明符 变量名,变量名…; 例如: static int a,b;           说明a,b为静态类型变量 auto char c1,c2;          说明c1,c2为自动字符变量 static int a[5]={1,2,3,4,5};    说明a为静整型数组 extern int x,y;           说明x,y为外部整型变量 下面分别介绍以上四种存储类型: 一、自动变量的类型说明符为auto。   这种存储类型是C语言程序中使用最广泛的一种类型。C语言规定, 函数内凡未加存储类型说明的变量均视为自动变量, 也就是说自动变量可省去说明符auto。 在前面各章的程序中所定义的变量凡未加存储类型说明符的都是自动变量。例如: { int i,j,k; char c; …… }等价于: { auto int i,j,k; auto char c; …… }   自动变量具有以下特点: 1. 自动变量的作用域仅限于定义该变量的个体内。在函数中定义的自动变量,只在该函数内有效。在复合语句中定义的自动变量只在该复合语句中有效。 例如: int kv(int a) { auto int x,y; { auto char c; } /*c的作用域*/ …… } /*a,x,y的作用域*/ 2. 自动变量属于动态存储方式,只有在使用它,即定义该变量的函数被调用时才给它分配存储单元,开始它的生存期。函数调用结束,释放存储单元,结束生存期。因此函数调用结束之后,自动变量的值不能保留。在复合语句中定义的自动变量,在退出复合语句后也不能再使用,否则将引起错误。例如以下程序: main() { auto int a,s,p; printf("\ninput a number:\n"); scanf("%d",&a); if(a>0){ s=a+a; p=a*a; } printf("s=%d p=%d\n",s,p); } { auto int a; printf("\ninput a number:\n"); scanf("%d",&a); if(a>0){ auto int s,p; s=a+a; p=a*a; } printf("s=%d p=%d\n",s,p); } s,p是在复合语句内定义的自动变量,只能在该复合语句内有效。而程序的第9行却是退出复合语句之后用printf语句输出s,p的值,这显然会引起错误。 3. 由于自动变量的作用域和生存期都局限于定义它的个体内( 函数或复合语句内), 因此不同的个体中允许使用同名的变量而不会混淆。 即使在函数内定义的自动变量也可与该函数内部的复合语句中定义的自动变量同名。例5.14表明了这种情况。 [例5.14] main() { auto int a,s=100,p=100; printf("\ninput a number:\n"); scanf("%d",&a); if(a>0) { auto int s,p; s=a+a; p=a*a; printf("s=%d p=%d\n",s,p); } printf("s=%d p=%d\n",s,p); }   本程序在main函数中和复合语句内两次定义了变量s,p为自动变量。按照C语言的规定,在复合语句内,应由复合语句中定义的s,p起作用,故s的值应为a+ a,p的值为a*a。退出复合语句后的s,p 应为main所定义的s,p,其值在初始化时给定,均为100。从输出结果可以分析出两个s和两个p虽变量名相同, 但却是两个不同的变量。 4. 对构造类型的自动变量如数组等,不可作初始化赋值。 二、外部变量外部变量的类型说明符为extern。 在前面介绍全局变量时已介绍过外部变量。这里再补充说明外部变量的几个特点: 1. 外部变量和全局变量是对同一类变量的两种不同角度的提法。全局变是是从它的作用域提出的,外部变量从它的存储方式提出的,表示了它的生存期。 2. 当一个源程序由若干个源文件组成时, 在一个源文件中定义的外部变量在其它的源文件中也有效。例如有一个源程序由源文件F1.C和F2.C组成: F1.C int a,b; /*外部变量定义*/ char c; /*外部变量定义*/ main() { …… } F2.C extern int a,b; /*外部变量说明*/ extern char c; /*外部变量说明*/ func (int x,y) { …… } 在F1.C和F2.C两个文件中都要使用a,b,c三个变量。在F1.C文件中把a,b,c都定义为外部变量。在F2.C文件中用extern把三个变量说明为外部变量,表示这些变量已在其它文件中定义,并把这些变量的类型和变量名,编译系统不再为它们分配内存空间。 对构造类型的外部变量, 如数组等可以在说明时作初始化赋值,若不赋初值,则系统自动定义它们的初值为0。 三、静态变量   静态变量的类型说明符是static。 静态变量当然是属于静态存储方式,但是属于静态存储方式的量不一定就是静态变量, 例如外部变量虽属于静态存储方式,但不一定是静态变量,必须由 static加以定义后才能成为静态外部变量,或称静态全局变量。 对于自动变量,前面已经介绍它属于动态存储方式。 但是也可以用static定义它为静态自动变量,或称静态局部变量,从而成为静态存储方式。 由此看来, 一个变量可由static进行再说明,并改变其原有的存储方式。 1. 静态局部变量   在局部变量的说明前再加上static说明符就构成静态局部变量。 例如: static int a,b; static float array[5]={1,2,3,4,5};      静态局部变量属于静态存储方式,它具有以下特点: (1)静态局部变量在函数内定义,但不象自动变量那样,当调用时就存在,退出函数时就消失。静态局部变量始终存在着,也就是说它的生存期为整个源程序。 (2)静态局部变量的生存期虽然为整个源程序,但是其作用域仍与自动变量相同,即只能在定义该变量的函数内使用该变量。退出该函数后, 尽管该变量还继续存在,但不能使用它。 (3)允许对构造类静态局部量赋初值。在数组一章中,介绍数组初始化时已作过说明。若未赋以初值,则由系统自动赋以0值。 (4)对基本类型的静态局部变量若在说明时未赋以初值,则系统自动赋予0值。而对自动变量不赋初值,则其值是不定的。 根据静态局部变量的特点, 可以看出它是一种生存期为整个源程序的量。虽然离开定义它的函数后不能使用,但如再次调用定义它的函数时,它又可继续使用, 而且保存了前次被调用后留下的值。 因此,当多次调用一个函数且要求在调用之间保留某些变量的值时,可考虑采用静态局部变量。虽然用全局变量也可以达到上述目的,但全局变量有时会造成意外的副作用,因此仍以采用局部静态变量为宜。 [例5.15]main() { int i; void f(); /*函数说明*/ for(i=1;i<=5;i++) f(); /*函数调用*/ } void f() /*函数定义*/ { auto int j=0; ++j; printf("%d\n",j); }   程序中定义了函数f,其中的变量j 说明为自动变量并赋予初始值为0。当main中多次调用f时,j均赋初值为0,故每次输出值均为1。现在把j改为静态局部变量,程序如下: main() { int i; void f(); for (i=1;i<=5;i++) f(); } void f() { static int j=0; ++j; printf("%d\n",j); } void f() { static int j=0; ++j; printf("%d/n",j); } 由于j为静态变量,能在每次调用后保留其值并在下一次调用时继续使用,所以输出值成为累加的结果。读者可自行分析其执行过程。 2.静态全局变量   全局变量(外部变量)的说明之前再冠以static 就构成了静态的全局变量。全局变量本身就是静态存储方式, 静态全局变量当然也是静态存储方式。 这两者在存储方式上并无不同。这两者的区别虽在于非静态全局变量的作用域是整个源程序, 当一个源程序由多个源文件组成时,非静态的全局变量在各个源文件中都是有效的。 而静态全局变量则限制了其作用域, 即只在定义该变量的源文件内有效, 在同一源程序的其它源文件中不能使用它。由于静态全局变量的作用域局限于一个源文件内,只能为该源文件内的函数公用, 因此可以避免在其它源文件中引起错误。从以上分析可以看出, 把局部变量改变为静态变量后是改变了它的存储方式即改变了它的生存期。把全局变量改变为静态变量后是改变了它的作用域, 限制了它 的使用范围。因此static 这个说明符在不同的地方所起的作用是不同的。应予以注意。 四、寄存器变量   上述各类变量都存放在存储器内, 因此当对一个变量频繁读写时,必须要反复访问内存储器,从而花费大量的存取时间。 为此,C语言提供了另一种变量,即寄存器变量。这种变量存放在CPU的寄存器中,使用时,不需要访问内存,而直接从寄存器中读写, 这样可提高效率。寄存器变量的说明符是register。 对于循环次数较多的循环控制变量及循环体内反复使用的变量均可定义为寄存器变量。 [例5.16]求∑200i=1imain() { register i,s=0; for(i=1;i<=200;i++) s=s+i; printf("s=%d\n",s); } 本程序循环200次,i和s都将频繁使用,因此可定义为寄存器变量。 对寄存器变量还要说明以下几点: 1. 只有局部自动变量和形式参数才可以定义为寄存器变量。因为寄存器变量属于动态存储方式。凡需要采用静态存储方式的量不能定义为寄存器变量。 2. 在Turbo C,MS C等微机上使用的C语言中, 实际上是把寄存器变量当成自动变量处理的。因此速度并不能提高。 而在程序中允许使用寄存器变量只是为了与标准C保持一致。3. 即使能真正使用寄存器变量的机器,由于CPU 中寄存器的个数是有限的,因此使用寄存器变量的个数也是有限的。 内部函数和外部函数   函数一旦定义后就可被其它函数调用。 但当一个源程序由多个源文件组成时, 在一个源文件中定义的函数能否被其它源文件中的函数调用呢?为此,C语言又把函数分为两类: 一、内部函数   如果在一个源文件中定义的函数只能被本文件中的函数调用,而不能被同一源程序其它文件中的函数调用, 这种函数称为内部函 数。定义内部函数的一般形式是: static 类型说明符 函数名(形参表) 例如: static int f(int a,int b) 内部函数也称为静态函数。但此处静态static 的含义已不是指存储方式,而是指对函数的调用范围只局限于本文件。 因此在不同的源文件中定义同名的静态函数不会引起混淆。 二、外部函数   外部函数在整个源程序中都有效,其定义的一般形式为: extern 类型说明符 函数名(形参表) 例如: extern int f(int a,int b)如在函数定义中没有说明extern或static则隐含为extern。在一个源文件的函数中调用其它源文件中定义的外部函数时,应 用extern说明被调函数为外部函数。例如: F1.C (源文件一) main() { extern int f1(int i); /*外部函数说明,表示f1函 数在其它源文件中*/ …… } F2.C (源文件二) extern int f1(int i); /*外部函数定义*/ { …… } 本章小结 1. 函数的分类 (1)库函数:由C系统提供的函数; (2)用户定义函数:由用户自己定义的函数; (3)有返回值的函数向调用者返回函数值,应说明函数类型( 即返回值的类型 ); (4)无返回值的函数:不返回函数值,说明为空(void)类型; (5)有参函数:主调函数向被调函数传送数据; (6)无参函数:主调函数与被调函数间无数据传送; (7)内部函数:只能在本源文件中使用的函数; (8)外部函数:可在整个源程序中使用的函数。 2. 函数定义的一般形式 [extern/static] 类型说明符 函数名([形参表]) 方括号内为可选项。 3. 函数说明的一般形式 [extern] 类型说明符 函数名([形参表]); 4. 函数调用的一般形式 函数名([实参表]) 5. 函数的参数分为形参和实参两种,形参出现在函数定义中,实参出现在函数调用中,发生函数调用时,将把实参的值传送给形参。 6. 函数的值是指函数的返回值,它是在函数中由return语句返回的。 7. 数组名作为函数参数时不进行值传送而进行地址传送。形参和实参实际上为同一数组的两个名称。因此形参数组的值发生变化,实参数组的值当然也变化。 8. C语言中,允许函数的嵌套调用和函数的递归调用。 9. 可从三个方面对变量分类,即变量的数据类型,变量作用域和变量的存储类型。在第二章中主要介绍变量的数据类型,本章中介绍了变量的作用域和变量的存储类型。 10.变量的作用域是指变量在程序中的有效范围, 分为局部变量和全局变量。 11.变量的存储类型是指变量在内存中的存储方式,分为静态存储和动态存储,表示了变量的生存期。 12.变量分类特性表存储方式存储类型说明符何处定义生存期作用域赋值前的值可赋初值类型动态存储自动变量 auto 寄存器变量 register 函数或复合语句内被调用时在定义它的函数或复合语句内不定基本类型int或char外部变量extern函数之外整个源程序整个源程序静态局部变量static 函数或复合语句内静态全局变量static 函数之外整个源程序在定义它的函数或复合语句内在定义它的源文件内0任何类型 第六章:指针 指针简介   指针是C语言中广泛使用的一种数据类型。 运用指针编程是C语言最主要的风格之一。利用指针变量可以表示各种数据结构; 能很方便地使用数组和字符串; 并能象汇编语言一样处理内存地址,从而编出精练而高效的程序。指针极大地丰富了C语言的功能。 学习指针是学习C语言中最重要的一环, 能否正确理解和使用指针是我们是否掌握C语言的一个标志。同时, 指针也是C语言中最为困难的一部分,在学习中除了要正确理解基本概念,还必须要多编程,上机调试。只要作到这些,指针也是不难掌握的。   指针的基本概念 在计算机中,所有的数据都是存放在存储器中的。 一般把存储器中的一个字节称为一个内存单元, 不同的数据类型所占用的内存单元数不等,如整型量占2个单元,字符量占1个单元等, 在第二章中已有详细的介绍。为了正确地访问这些内存单元, 必须为每个内存单元编上号。 根据一个内存单元的编号即可准确地找到该内存单元。内存单元的编号也叫做地址。 既然根据内存单元的编号或地址就可以找到所需的内存单元,所以通常也把这个地址称为指针。 内存单元的指针和内存单元的内容是两个不同的概念。 可以用一个通俗的例子来说明它们之间的关系。我们到银行去存取款时, 银行工作人员将根据我们的帐号去找我们的存款单, 找到之后在存单上写入存款、取款的金额。在这里,帐号就是存单的指针, 存款数是存单的内容。对于一个内存单元来说,单元的地址即为指针, 其中存放的数据才是该单元的内容。在C语言中, 允许用一个变量来存放指针,这种变量称为指针变量。因此, 一个指针变量的值就是某个内存单元的地址或称为某内存单元的指针。图中,设有字符变量C,其内容为“K”(ASCII码为十进制数 75),C占用了011A号单元(地址用十六进数表示)。设有指针变量P,内容为011A, 这种情况我们称为P指向变量C,或说P是指向变量C的指针。 严格地说,一个指针是一个地址, 是一个常量。而一个指针变量却可以被赋予不同的指针值,是变。 但在常把指针变量简称为指针。为了避免混淆,我们中约定:“指针”是指地址, 是常量,“指针变量”是指取值为地址的变量。 定义指针的目的是为了通过指针去访问内存单元。     既然指针变量的值是一个地址, 那么这个地址不仅可以是变量的地址, 也可以是其它数据结构的地址。在一个指针变量中存放一 个数组或一个函数的首地址有何意义呢? 因为数组或函数都是连续存放的。通过访问指针变量取得了数组或函数的首地址, 也就找到了该数组或函数。这样一来, 凡是出现数组,函数的地方都可以用一个指针变量来表示, 只要该指针变量中赋予数组或函数的首地址即可。这样做, 将会使程序的概念十分清楚,程序本身也精练,高效。在C语言中, 一种数据类型或数据结构往往都占有一组连续的内存单元。 用“地址”这个概念并不能很好地描述一种数据类型或数据结构, 而“指针”虽然实际上也是一个地址,但它却是一个数据结构的首地址, 它是“指向”一个数据结构的,因而概念更为清楚,表示更为明确。 这也是引入“指针”概念的一个重要原因。 指针变量的类型说明   对指针变量的类型说明包括三个内容: (1)指针类型说明,即定义变量为一个指针变量; (2)指针变量名; (3)变量值(指针)所指向的变量的数据类型。   其一般形式为: 类型说明符 *变量名;   其中,*表示这是一个指针变量,变量名即为定义的指针变量名,类型说明符表示本指针变量所指向的变量的数据类型。   例如: int *p1;表示p1是一个指针变量,它的值是某个整型变量的地址。 或者说p1指向一个整型变量。至于p1究竟指向哪一个整型变量, 应由向p1赋予的地址来决定。   再如: staic int *p2; /*p2是指向静态整型变量的指针变量*/ float *p3; /*p3是指向浮点变量的指针变量*/ char *p4; /*p4是指向字符变量的指针变量*/ 应该注意的是,一个指针变量只能指向同类型的变量,如P3 只能指向浮点变量,不能时而指向一个浮点变量, 时而又指向一个字符变量。 指针变量的赋值   指针变量同普通变量一样,使用之前不仅要定义说明, 而且必须赋予具体的值。未经赋值的指针变量不能使用, 否则将造成系统混乱,甚至死机。指针变量的赋值只能赋予地址, 决不能赋予任何其它数据,否则将引起错误。在C语言中, 变量的地址是由编译系统分配的,对用户完全透明,用户不知道变量的具体地址。 C语言中提供了地址运算符&来表示变量的地址。其一般形式为: & 变量名; 如&a变示变量a的地址,&b表示变量b的地址。 变量本身必须预先说明。设有指向整型变量的指针变量p,如要把整型变量a 的地址赋予p可以有以下两种方式: (1)指针变量初始化的方法 int a; int *p=&a; (2)赋值语句的方法 int a; int *p; p=&a; 不允许把一个数赋予指针变量,故下面的赋值是错误的: int *p;p=1000; 被赋值的指针变量前不能再加“*”说明符,如写为*p=&a 也是错误的 指针变量的运算   指针变量可以进行某些运算,但其运算的种类是有限的。 它只能进行赋值运算和部分算术运算及关系运算。 1.指针运算符 (1)取地址运算符&   取地址运算符&是单目运算符,其结合性为自右至左,其功能是取变量的地址。在scanf函数及前面介绍指针变量赋值中,我们已经了解并使用了&运算符。 (2)取内容运算符*   取内容运算符*是单目运算符,其结合性为自右至左,用来表示指针变量所指的变量。在*运算符之后跟的变量必须是指针变量。需要注意的是指针运算符*和指针变量说明中的指针说明符* 不是一回事。在指针变量说明中,“*”是类型说明符,表示其后的变量是指针类型。而表达式中出现的“*”则是一个运算符用以表示指针变量所指的变量。 main(){ int a=5,*p=&a; printf ("%d",*p); } ...... 表示指针变量p取得了整型变量a的地址。本语句表示输出变量a的值。 2.指针变量的运算 (1)赋值运算 指针变量的赋值运算有以下几种形式: ①指针变量初始化赋值,前面已作介绍。 ②把一个变量的地址赋予指向相同数据类型的指针变量。例如: int a,*pa; pa=&a; /*把整型变量a的地址赋予整型指针变量pa*/ ③把一个指针变量的值赋予指向相同类型变量的另一个指针变量。如: int a,*pa=&a,*pb; pb=pa; /*把a的地址赋予指针变量pb*/ 由于pa,pb均为指向整型变量的指针变量,因此可以相互赋值。 ④把数组的首地址赋予指向数组的指针变量。 例如: int a[5],*pa; pa=a; (数组名表示数组的首地址,故可赋予指向数组的指针变量pa) 也可写为: pa=&a[0]; /*数组第一个元素的地址也是整个数组的首地址, 也可赋予pa*/ 当然也可采取初始化赋值的方法: int a[5],*pa=a; ⑤把字符串的首地址赋予指向字符类型的指针变量。例如: char *pc;pc="c language";或用初始化赋值的方法写为: char *pc="C Language"; 这里应说明的是并不是把整个字符串装入指针变量, 而是把存放该字符串的字符数组的首地址装入指针变量。 在后面还将详细介绍。 ⑥把函数的入口地址赋予指向函数的指针变量。例如: int (*pf)();pf=f; /*f为函数名*/ (2)加减算术运算   对于指向数组的指针变量,可以加上或减去一个整数n。设pa是指向数组a的指针变量,则pa+n,pa-n,pa++,++pa,pa--,--pa 运算都是合法的。指针变量加或减一个整数n的意义是把指针指向的当前位置(指向某数组元素)向前或向后移动n个位置。应该注意,数组指针变量向前或向后移动一个位置和地址加1或减1 在概念上是不同的。因为数组可以有不同的类型, 各种类型的数组元素所占的字节长度是不同的。如指针变量加1,即向后移动1 个位置表示指针变量指向下一个数据元素的首地址。而不是在原地址基础上加1。 例如: int a[5],*pa; pa=a; /*pa指向数组a,也是指向a[0]*/ pa=pa+2; /*pa指向a[2],即pa的值为&pa[2]*/ 指针变量的加减运算只能对数组指针变量进行, 对指向其它类型变量的指针变量作加减运算是毫无意义的。(3)两个指针变量之间的运算只有指向同一数组的两个指针变量之间才能进行运算, 否则运算毫无意义。 ①两指针变量相减 两指针变量相减所得之差是两个指针所指数组元素之间相差的元素个数。实际上是两个指针值(地址) 相减之差再除以该数组元素的长度(字节数)。例如pf1和pf2 是指向同一浮点数组的两个指针变量,设pf1的值为2010H,pf2的值为2000H,而浮点数组每个元素占4个字节,所以pf1-pf2的结果为(2000H-2010H)/4=4,表示pf1和 pf2之间相差4个元素。两个指针变量不能进行加法运算。 例如, pf1+pf2是什么意思呢?毫无实际意义。 ②两指针变量进行关系运算 指向同一数组的两指针变量进行关系运算可表示它们所指数组元素之间的关系。例如: pf1==pf2表示pf1和pf2指向同一数组元素 pf1>pf2表示pf1处于高地址位置 pf1b){ pmax=&a; pmin=&b;} else{ pmax=&b; pmin=&a;} if(c>*pmax) pmax=&c; if(c<*pmin) pmin=&c; printf("max=%d\nmin=%d\n",*pmax,*pmin); } ...... pmax,pmin为整型指针变量。 输入提示。 输入三个数字。 如果第一个数字大于第二个数字... 指针变量赋值 指针变量赋值 指针变量赋值 指针变量赋值 判断并赋值 判断并赋值 输出结果 ...... 数组指针变量的说明和使用   指向数组的指针变量称为数组指针变量。 在讨论数组指针变量的说明和使用之前,我们先明确几个关系。 一个数组是由连续的一块内存单元组成的。 数组名就是这块连续内存单元的首地址。一个数组也是由各个数组元素(下标变量) 组成的。每个数组元素按其类型不同占有几个连续的内存单元。 一个数组元素的首地址也是指它所占有的几个内存单元的首地址。 一个指针变量既可以指向一个数组,也可以指向一个数组元素, 可把数组名或第一个元素的地址赋予它。如要使指针变量指向第i号元素可以把i元素的首地址赋予它或把数组名加i赋予它。   设有实数组a,指向a的指针变量为pa,从图6.3中我们可以看出有以下关系: pa,a,&a[0]均指向同一单元,它们是数组a的首地址,也是0 号元素a[0]的首地址。pa+1,a+1,&a[1]均指向1号元素a[1]。类推可知a+i,a+i,&a[i] 指向i号元素a[i]。应该说明的是pa是变量,而a,&a[i]都是常量。在编程时应予以注意。 main(){ int a[5],i; for(i=0;i<5;i++){ a[i]=i; printf("a[%d]=%d\n",i,a[i]); } printf("\n"); } 主函数 定义一个整型数组和一个整型变量 循环语句 给数组赋值 打印每一个数组的值 ...... 输出换行 ...... 数组指针变量说明的一般形式为: 类型说明符 * 指针变量名   其中类型说明符表示所指数组的类型。 从一般形式可以看出指向数组的指针变量和指向普通变量的指针变量的说明是相同的。 引入指针变量后,就可以用两种方法来访问数组元素了。   第一种方法为下标法,即用a[i]形式访问数组元素。 在第四章中介绍数组时都是采用这种方法。   第二种方法为指针法,即采用*(pa+i)形式,用间接访问的方法来访问数组元素。 main(){ int a[5],i,*pa; pa=a; for(i=0;i<5;i++){ *pa=i; pa++; } pa=a; for(i=0;i<5;i++){ printf("a[%d]=%d\n",i,*pa); pa++; } } 主函数 定义整型数组和指针 将指针pa指向数组a 循环 将变量i的值赋给由指针pa指向的a[]的数组单元 将指针pa指向a[]的下一个单元 ...... 指针pa重新取得数组a的首地址 循环 用数组方式输出数组a中的所有元素 将指针pa指向a[]的下一个单元 ...... ...... 下面,另举一例,该例与上例本意相同,但是实现方式不同。 main(){ int a[5],i,*pa=a; for(i=0;i<5;){ *pa=i; printf("a[%d]=%d\n",i++,*pa++); } } 主函数 定义整型数组和指针,并使指针指向数组a 循环 将变量i的值赋给由指针pa指向的a[]的数组单元 用指针输出数组a中的所有元素,同时指针pa指向a[]的下一个单元 ...... ...... 数组名和数组指针变量作函数参数   在第五章中曾经介绍过用数组名作函数的实参和形参的问题。在学习指针变量之后就更容易理解这个问题了。 数组名就是数组的首地址,实参向形参传送数组名实际上就是传送数组的地址, 形参得到该地址后也指向同一数组。 这就好象同一件物品有两个彼此不同的名称一样。同样,指针变量的值也是地址, 数组指针变量的值即为数组的首地址,当然也可作为函数的参数使用。 float aver(float *pa); main(){ float sco[5],av,*sp; int i; sp=sco; printf("\ninput 5 scores:\n"); for(i=0;i<5;i++) scanf("%f",&sco[i]); av=aver(sp); printf("average score is %5.2f",av); } float aver(float *pa) { int i; float av,s=0; for(i=0;i<5;i++) s=s+*pa++; av=s/5; return av; } 指向多维数组的指针变量 本小节以二维数组为例介绍多维数组的指针变量。 一、多维数组地址的表示方法 设有整型二维数组a[3][4]如下: 0 1 2 3 4 5 6 7 8 9 10 11   设数组a的首地址为1000,各下标变量的首地址及其值如图所示。在第四章中介绍过, C语言允许把一个二维数组分解为多个一维数组来处理。因此数组a可分解为三个一维数组,即a[0],a[1],a[2]。每一个一维数组又含有四个元素。例如a[0]数组,含有a[0][0],a[0][1],a[0][2],a[0][3]四个元素。 数组及数组元素的地址表示如下:a是二维数组名,也是二维数组0行的首地址,等于1000。a[0]是第一个一维数组的数组名和首地址,因此也为1000。*(a+0)或*a是与a[0]等效的, 它表示一维数组a[0]0 号元素的首地址。 也为1000。&a[0][0]是二维数组a的0行0列元素首地址,同样是1000。因此,a,a[0],*(a+0),*a,&a[0][0]是相等的。同理,a+1是二维数组1行的首地址,等于1008。a[1]是第二个一维数组的数组名和首地址,因此也为1008。 &a[1][0]是二维数组a的1行0列元素地址,也是1008。因此a+1,a[1],*(a+1),&a[1][0]是等同的。 由此可得出:a+i,a[i],*(a+i),&a[i][0]是等同的。 此外,&a[i]和a[i]也是等同的。因为在二维数组中不能把&a[i]理解为元素a[i]的地址,不存在元素a[i]。   C语言规定,它是一种地址计算方法,表示数组a第i行首地址。由此,我们得出:a[i],&a[i],*(a+i)和a+i也都是等同的。另外,a[0]也 可以看成是a[0]+0是一维数组a[0]的0号元素的首地址, 而a[0]+1则是a[0]的1号元素首地址,由此可得出a[i]+j则是一维数组a[i]的j号元素首地址,它等于&a[i][j]。由a[i]=*(a+i)得a[i]+j=*(a+i)+j,由于*(a+i)+j是二维数组a的i行j列元素的首地址。该元素的值等于*(*(a+i)+j)。 [Explain]#define PF "%d,%d,%d,%d,%d,\n" main(){ static int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11}; printf(PF,a,*a,a[0],&a[0],&a[0][0]); printf(PF,a+1,*(a+1),a[1],&a[1],&a[1][0]); printf(PF,a+2,*(a+2),a[2],&a[2],&a[2][0]); printf("%d,%d\n",a[1]+1,*(a+1)+1); printf("%d,%d\n",*(a[1]+1),*(*(a+1)+1)); } 二、多维数组的指针变量   把二维数组a 分解为一维数组a[0],a[1],a[2]之后,设p为指向二维数组的指针变量。可定义为: int (*p)[4] 它表示p是一个指针变量,它指向二维数组a 或指向第一个一维数组a[0],其值等于a,a[0],或&a[0][0]等。而p+i则指向一维数组a[i]。从前面的分析可得出*(p+i)+j是二维数组i行j 列的元素的地址,而*(*(p+i)+j)则是i行j列元素的值。   二维数组指针变量说明的一般形式为: 类型说明符 (*指针变量名)[长度] 其中“类型说明符”为所指数组的数据类型。“*”表示其后的变量是指针类型。 “长度”表示二维数组分解为多个一维数组时, 一维数组的长度,也就是二维数组的列数。应注意“(*指针变量名)”两边的括号不可少,如缺少括号则表示是指针数组(本章后面介绍),意义就完全不同了。 [Explain]main(){ static int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11}; int(*p)[4]; int i,j; p=a; for(i=0;i<3;i++) for(j=0;j<4;j++) printf("%2d ",*(*(p+i)+j)); } 'Expain字符串指针变量的说明和使用字符串指针变量的定义说明与指向字符变量的指针变量说明是相同的。只能按对指针变量的赋值不同来区别。 对指向字符变量的指针变量应赋予该字符变量的地址。如: char c,*p=&c;表示p是一个指向字符变量c的指针变量。而: char *s="C Language";则表示s是一个指向字符串的指针变量。把字符串的首地址赋予s。 请看下面一例。 main(){ char *ps; ps="C Language"; printf("%s",ps); } 运行结果为: C Language 上例中,首先定义ps是一个字符指针变量, 然后把字符串的首地址赋予ps(应写出整个字符串,以便编译系统把该串装入连续的一块内存单元),并把首地址送入ps。程序中的: char *ps;ps="C Language";等效于: char *ps="C Language";输出字符串中n个字符后的所有字符。 main(){ char *ps="this is a book"; int n=10; ps=ps+n; printf("%s\n",ps); } 运行结果为: book 在程序中对ps初始化时,即把字符串首地址赋予ps,当ps= ps+10之后,ps指向字符“b”,因此输出为"book"。 main(){ char st[20],*ps; int i; printf("input a string:\n"); ps=st; scanf("%s",ps); for(i=0;ps[i]!='\0';i++) if(ps[i]=='k'){ printf("there is a 'k' in the string\n"); break; } if(ps[i]=='\0') printf("There is no 'k' in the string\n"); }   本例是在输入的字符串中查找有无‘k’字符。 下面这个例子是将指针变量指向一个格式字符串,用在printf函数中,用于输出二维数组的各种地址表示的值。但在printf语句中用指针变量PF代替了格式串。 这也是程序中常用的方法。 main(){ static int a[3][4]={0,1,2,3,4,5,6,7,8,9,10,11}; char *PF; PF="%d,%d,%d,%d,%d\n"; printf(PF,a,*a,a[0],&a[0],&a[0][0]); printf(PF,a+1,*(a+1),a[1],&a[1],&a[1][0]); printf(PF,a+2,*(a+2),a[2],&a[2],&a[2][0]); printf("%d,%d\n",a[1]+1,*(a+1)+1); printf("%d,%d\n",*(a[1]+1),*(*(a+1)+1)); }   在下例是讲解,把字符串指针作为函数参数的使用。要求把一个字符串的内容复制到另一个字符串中,并且不能使用strcpy函数。函数cprstr的形参为两个字符指针变量。pss指向源字符串,pds指向目标字符串。表达式: (*pds=*pss)!=`\0' cpystr(char *pss,char *pds){ while((*pds=*pss)!='\0'){ pds++; pss++; } } main(){ char *pa="CHINA",b[10],*pb; pb=b; cpystr(pa,pb); printf("string a=%s\nstring b=%s\n",pa,pb); }   在上例中,程序完成了两项工作:一是把pss指向的源字符复制到pds所指向的目标字符中,二是判断所复制的字符是否为`\0',若是则表明源字符串结束,不再循环。否则,pds和pss都加1,指向下一字符。在主函数中,以指针变量pa,pb为实参,分别取得确定值后调用cprstr函数。由于采用的指针变量pa和pss,pb和pds均指向同一字符串,因此在主函数和cprstr函数中均可使用这些字符串。也可以把cprstr函数简化为以下形式: cprstr(char *pss,char*pds) {while ((*pds++=*pss++)!=`\0');}   即把指针的移动和赋值合并在一个语句中。 进一步分析还可发现`\0'的ASCⅡ码为0,对于while语句只看表达式的值为非0就循环,为0则结束循环,因此也可省去“!=`\0'”这一判断部分,而写为以下形式: cprstr (char *pss,char *pds) {while (*pdss++=*pss++);} 表达式的意义可解释为,源字符向目标字符赋值, 移动指针,若所赋值为非0则循环,否则结束循环。这样使程序更加简洁。简化后的程序如下所示。 cpystr(char *pss,char *pds){ while(*pds++=*pss++); } main(){ char *pa="CHINA",b[10],*pb; pb=b; cpystr(pa,pb); printf("string a=%s\nstring b=%s\n",pa,pb); } 使用字符串指针变量与字符数组的区别 用字符数组和字符指针变量都可实现字符串的存储和运算。 但是两者是有区别的。在使用时应注意以下几个问题: 1. 字符串指针变量本身是一个变量,用于存放字符串的首地址。而字符串本身是存放在以该首地址为首的一块连续的内存空间中并以‘\0’作为串的结束。字符数组是由于若干个数组元素组成的,它可用来存放整个字符串。 2. 对字符数组作初始化赋值,必须采用外部类型或静态类型,如: static char st[]={“C Language”};而对字符串指针变量则无此限制,如: char *ps="C Language"; 3. 对字符串指针方式 char *ps="C Language";可以写为: char *ps; ps="C Language";而对数组方式: static char st[]={"C Language"}; 不能写为: char st[20];st={"C Language"}; 而只能对字符数组的各元素逐个赋值。   从以上几点可以看出字符串指针变量与字符数组在使用时的区别,同时也可看出使用指针变量更加方便。前面说过,当一个指针变量在未取得确定地址前使用是危险的,容易引起错误。但是对指针变量直接赋值是可以的。因为C系统对指针变量赋值时要给以确定的地址。因此, char *ps="C Langage"; 或者 char *ps; ps="C Language";都是合法的。 函数指针变量   在C语言中规定,一个函数总是占用一段连续的内存区, 而函数名就是该函数所占内存区的首地址。 我们可以把函数的这个首地址(或称入口地址)赋予一个指针变量, 使该指针变量指向该函数。然后通过指针变量就可以找到并调用这个函数。 我们把这种指向函数的指针变量称为“函数指针变量”。 函数指针变量定义的一般形式为: 类型说明符 (*指针变量名)(); 其中“类型说明符”表示被指函数的返回值的类型。“(* 指针变量名)”表示“*”后面的变量是定义的指针变量。 最后的空括号表示指针变量所指的是一个函数。 例如: int (*pf)(); 表示pf是一个指向函数入口的指针变量,该函数的返回值(函数值)是整型。 下面通过例子来说明用指针形式实现对函数调用的方法。 int max(int a,int b){ if(a>b)return a; else return b; } main(){ int max(int a,int b); int(*pmax)(); int x,y,z; pmax=max; printf("input two numbers:\n"); scanf("%d%d",&x,&y); z=(*pmax)(x,y); printf("maxmum=%d",z); }   从上述程序可以看出用,函数指针变量形式调用函数的步骤如下:1. 先定义函数指针变量,如后一程序中第9行 int (*pmax)();定义pmax为函数指针变量。 2. 把被调函数的入口地址(函数名)赋予该函数指针变量,如程序中第11行 pmax=max; 3. 用函数指针变量形式调用函数,如程序第14行 z=(*pmax)(x,y); 调用函数的一般形式为: (*指针变量名) (实参表)使用函数指针变量还应注意以下两点: a. 函数指针变量不能进行算术运算,这是与数组指针变量不同的。数组指针变量加减一个整数可使指针移动指向后面或前面的数组元素,而函数指针的移动是毫无意义的。 b. 函数调用中"(*指针变量名)"的两边的括号不可少,其中的*不应该理解为求值运算,在此处它只是一种表示符号。 指针型函数 前面我们介绍过,所谓函数类型是指函数返回值的类型。 在C语言中允许一个函数的返回值是一个指针(即地址), 这种返回指针值的函数称为指针型函数。 定义指针型函数的一般形式为: 类型说明符 *函数名(形参表) { …… /*函数体*/ } 其中函数名之前加了“*”号表明这是一个指针型函数,即返回值是一个指针。类型说明符表示了返回的指针值所指向的数据类型。 如: int *ap(int x,int y) { ...... /*函数体*/ }   表示ap是一个返回指针值的指针型函数, 它返回的指针指向一个整型变量。下例中定义了一个指针型函数 day_name,它的返回值指向一个字符串。该函数中定义了一个静态指针数组name。name 数组初始化赋值为八个字符串,分别表示各个星期名及出错提示。形参n表示与星期名所对应的整数。在主函数中, 把输入的整数i作为实参, 在printf语句中调用day_name函数并把i值传送给形参 n。day_name函数中的return语句包含一个条件表达式, n 值若大于7或小于1则把name[0] 指针返回主函数输出出错提示字符串“Illegal day”。否则返回主函数输出对应的星期名。主函数中的第7行是个条件语句,其语义是,如输入为负数(i<0)则中止程序运行退出程序。exit是一个库函数,exit(1)表示发生错误后退出程序, exit(0)表示正常退出。   应该特别注意的是函数指针变量和指针型函数这两者在写法和意义上的区别。如int(*p)()和int *p()是两个完全不同的量。int(*p)()是一个变量说明,说明p 是一个指向函数入口的指针变量,该函数的返回值是整型量,(*p)的两边的括号不能少。int *p() 则不是变量说明而是函数说明,说明p是一个指针型函数,其返回值是一个指向整型量的指针,*p两边没有括号。作为函数说明, 在括号内最好写入形式参数,这样便于与变量说明区别。 对于指针型函数定义,int *p()只是函数头部分,一般还应该有函数体部分。 main(){ int i; char *day_name(int n); printf("input Day No:\n"); scanf("%d",&i); if(i<0) exit(1); printf("Day No:%2d-->%s\n",i,day_name(i)); } char *day_name(int n){ static char *name[]={ "Illegal day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; return((n<1||n>7) ? name[0] : name[n]); }   本程序是通过指针函数,输入一个1~7之间的整数, 输出对应的星期名。指针数组的说明与使用一个数组的元素值为指针则是指针数组。 指针数组是一组有序的指针的集合。 指针数组的所有元素都必须是具有相同存储类型和指向相同数据类型的指针变量。   指针数组说明的一般形式为: 类型说明符*数组名[数组长度]   其中类型说明符为指针值所指向的变量的类型。例如: int *pa[3] 表示pa是一个指针数组,它有三个数组元素, 每个元素值都是一个指针,指向整型变量。通常可用一个指针数组来指向一个二维数组。 指针数组中的每个元素被赋予二维数组每一行的首地址, 因此也可理解为指向一个一维数组。图6—6表示了这种关系。 int a[3][3]={1,2,3,4,5,6,7,8,9}; int *pa[3]={a[0],a[1],a[2]}; int *p=a[0]; main(){ int i; for(i=0;i<3;i++) printf("%d,%d,%d\n",a[i][2-i],*a[i],*(*(a+i)+i)); for(i=0;i<3;i++) printf("%d,%d,%d\n",*pa[i],p[i],*(p+i)); }   本例程序中,pa是一个指针数组,三个元素分别指向二维数组a的各行。然后用循环语句输出指定的数组元素。其中*a[i]表示i行0列元素值;*(*(a+i)+i)表示i行i列的元素值;*pa[i]表示i行0列元素值;由于p与a[0]相同,故p[i]表示0行i列的值;*(p+i)表示0行i列的值。读者可仔细领会元素值的各种不同的表示方法。 应该注意指针数组和二维数组指针变量的区别。 这两者虽然都可用来表示二维数组,但是其表示方法和意义是不同的。   二维数组指针变量是单个的变量,其一般形式中"(*指针变量名)"两边的括号不可少。而指针数组类型表示的是多个指针( 一组有序指针)在一般形式中"*指针数组名"两边不能有括号。例如: int (*p)[3];表示一个指向二维数组的指针变量。该二维数组的列数为3或分解为一维数组的长度为3。 int *p[3] 表示p是一个指针数组,有三个下标变量p[0],p[1],p[2]均为指针变量。   指针数组也常用来表示一组字符串, 这时指针数组的每个元素被赋予一个字符串的首地址。 指向字符串的指针数组的初始化更为简单。例如在例6.20中即采用指针数组来表示一组字符串。 其初始化赋值为: char *name[]={"Illagal day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};   完成这个初始化赋值之后,name[0]即指向字符串"Illegal day",name[1]指?quot;Monday"......。   指针数组也可以用作函数参数。在本例主函数中,定义了一个指针数组name,并对name 作了初始化赋值。其每个元素都指向一个字符串。然后又以name 作为实参调用指针型函数day name,在调用时把数组名 name 赋予形参变量name,输入的整数i作为第二个实参赋予形参n。在day name函数中定义了两个指针变量pp1和pp2,pp1被赋予name[0]的值(即*name),pp2被赋予name[n]的值即*(name+ n)。由条件表达式决定返回pp1或pp2指针给主函数中的指针变量ps。最后输出i和ps的值。 指针数组作指针型函数的参数 main(){ static char *name[]={ "Illegal day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; char *ps; int i; char *day name(char *name[],int n); printf("input Day No:\n"); scanf("%d",&i); if(i<0) exit(1); ps=day name(name,i); printf("Day No:%2d-->%s\n",i,ps); } char *day name(char *name[],int n) { char *pp1,*pp2; pp1=*name; pp2=*(name+n); return((n<1||n>7)? pp1:pp2); } 下例要求输入5个国名并按字母顺序排列后输出。在以前的例子中采用了普通的排序方法, 逐个比较之后交换字符串的位置。交换字符串的物理位置是通过字符串复制函数完成的。 反复的交换将使程序执行的速度很慢,同时由于各字符串(国名) 的长度不同,又增加了存储管理的负担。 用指针数组能很好地解决这些问题。把所有的字符串存放在一个数组中, 把这些字符数组的首地址放在一个指针数组中,当需要交换两个字符串时, 只须交换指针数组相应两元素的内容(地址)即可,而不必交换字符串本身。程序中定义了两个函数,一个名为sort完成排序, 其形参为指 针数组name,即为待排序的各字符串数组的指针。形参n为字符串的个数。另一个函数名为print,用于排序后字符串的输出,其形参与sort的形参相同。主函数main中,定义了指针数组name 并作了初始化赋值。然后分别调用sort函数和print函数完成排序和输出。值得说明的是在sort函数中,对两个字符串比较,采用了strcmp 函数,strcmp函数允许参与比较的串以指针方式出现。name[k]和name[ j]均为指针,因此是合法的。字符串比较后需要交换时, 只交换指针数组元素的值,而不交换具体的字符串, 这样将大大减少时间的开销,提高了运行效率。 现编程如下: #include"string.h" main(){ void sort(char *name[],int n); void print(char *name[],int n); static char *name[]={ "CHINA","AMERICA","AUSTRALIA", "FRANCE","GERMAN"}; int n=5; sort(name,n); print(name,n); } void sort(char *name[],int n){ char *pt; int i,j,k; for(i=0;i0) k=j; if(k!=i){ pt=name[i]; name[i]=name[k]; name[k]=pt; } } } void print(char *name[],int n){ int i; for (i=0;i可执行文件名 参数 参数……; 但是应该特别注意的是,main 的两个形参和命令行中的参数在 位置上不是一一对应的。因为,main的形参只有二个,而命令行中的参数个数原则上未加限制。argc参数表示了命令行中参数的个数(注意:文件名本身也算一个参数),argc的值是在输入命令行时由系统按实际参数的个数自动赋予的。例如有命令行为: C:\>E6 24 BASIC dbase FORTRAN由于文件名E6 24本身也算一个参数,所以共有4个参数,因此argc取得的值为4。argv参数是字符串指针数组,其各元素值为命令行中各字符串(参数均按字符串处理)的首地址。 指针数组的长度即为参数个数。数组元素初值由系统自动赋予。其表示如图6.8所示: main(int argc,char *argv){ while(argc-->1) printf("%s\n",*++argv); } 本例是显示命令行中输入的参数如果上例的可执行文件名为e24.exe,存放在A驱动器的盘内。 因此输入的命令行为: C:\>a:e24 BASIC dBASE FORTRAN 则运行结果为: BASIC dBASE FORTRAN   该行共有4个参数,执行main时,argc的初值即为4。argv的4个元素分为4个字符串的首地址。执行while语句,每循环一次 argv值减1,当argv等于1时停止循环,共循环三次, 因此共可输出三个参数。在printf函数中,由于打印项*++argv是先加1再打印, 故第一次打印的是argv[1]所指的字符串BASIC。第二、 三次循环分别打印后二个字符串。而参数e24是文件名,不必输出。   下例的命令行中有两个参数,第二个参数20即为输入的n值。在程序中*++argv的值为字符串“20”,然后用函数"atoi"把它换为整型作为while语句中的循环控制变量,输出20个偶数。 #include"stdlib.h" main(int argc,char*argv[]){ int a=0,n; n=atoi(*++argv); while(n--) printf("%d ",a++*2); }   本程序是从0开始输出n个偶数。指向指针的指针变量如果一个指针变量存放的又是另一个指针变量的地址, 则称这个指针变量为指向指针的指针变量。   在前面已经介绍过,通过指针访问变量称为间接访问, 简称间访。由于指针变量直接指向变量,所以称为单级间访。 而如果通过指向指针的指针变量来访问变量则构成了二级或多级间访。在C语言程序中,对间访的级数并未明确限制, 但是间访级数太多时不容易理解解,也容易出错,因此,一般很少超过二级间访。 指向指针的指针变量说明的一般形式为: 类型说明符** 指针变量名; 例如: int ** pp; 表示pp是一个指针变量,它指向另一个指针变量, 而这个指针变量指向一个整型量。下面举一个例子来说明这种关系。 main(){ int x,*p,**pp; x=10; p=&x; pp=&p; printf("x=%d\n",**pp); }   上例程序中p 是一个指针变量,指向整型量x;pp也是一个指针变量, 它指向指针变量p。通过pp变量访问x的写法是**pp。程序最后输出x的值为10。通过上例,读者可以学习指向指针的指针变量的说明和使用方法。   下述程序中首先定义说明了指针数组ps并作了初始化赋值。 又说明了pps是一个指向指针的指针变量。在5次循环中, pps 分别取得了ps[0],ps[1],ps[2],ps[3],ps[4]的地址值(如图6.10所示)。再通过这些地址即可找到该字符串。 main(){ static char *ps[]={ "BASIC","DBASE","C","FORTRAN", "PASCAL"}; char **pps; int i; for(i=0;i<5;i++){ pps=ps+i; printf("%s\n",*pps); } } 本程序是用指向指针的指针变量编程,输出多个字符串。 本章小结 1. 指针是C语言中一个重要的组成部分,使用指针编程有以下优点: (1)提高程序的编译效率和执行速度。 (2)通过指针可使用主调函数和被调函数之间共享变量或数据结构,便于实现双向数据通讯。 (3)可以实现动态的存储分配。 (4)便于表示各种数据结构,编写高质量的程序。 2. 指针的运算 (1)取地址运算符&:求变量的地址 (2)取内容运算符*:表示指针所指的变量 (3)赋值运算 ·把变量地址赋予指针变量 ·同类型指针变量相互赋值 ·把数组,字符串的首地址赋予指针变量 ·把函数入口地址赋予指针变量 (4)加减运算 对指向数组,字符串的指针变量可以进行加减运算,如p+n,p-n,p++,p--等。对指向同一数组的两个指针变量可以相减。对指向其它类型的指针变量作加减运算是无意义的。 (5)关系运算 指向同一数组的两个指针变量之间可以进行大于、小于、 等于比较运算。指针可与0比较,p==0表示p为空指针。 3. 与指针有关的各种说明和意义见下表。 int *p;     p为指向整型量的指针变量 int *p[n];   p为指针数组,由n个指向整型量的指针元素组成。 int (*p)[n];  p为指向整型二维数组的指针变量,二维数组的列数为n int *p()    p为返回指针值的函数,该指针指向整型量 int (*p)()   p为指向函数的指针,该函数返回整型量 int **p     p为一个指向另一指针的指针变量,该指针指向一个整型量。 4. 有关指针的说明很多是由指针,数组,函数说明组合而成的。 但并不是可以任意组合,例如数组不能由函数组成,即数组元素不能是一个函数;函数也不能返回一个数组或返回另一个函数。例如 int a[5]();就是错误的。 5. 关于括号 在解释组合说明符时, 标识符右边的方括号和圆括号优先于标识符左边的“*”号,而方括号和圆括号以相同的优先级从左到右结合。但可以用圆括号改变约定的结合顺序。 6. 阅读组合说明符的规则是“从里向外”。 从标识符开始,先看它右边有无方括号或园括号,如有则先作出解释,再看左边有无*号。 如果在任何时候遇到了闭括号,则在继续之前必须用相同的规则处理括号内的内容。例如: int*(*(*a)())[10] ↑ ↑↑↑↑↑↑ 7 6 4 2 1 3 5 上面给出了由内向外的阅读顺序,下面来解释它: (1)标识符a被说明为; (2)一个指针变量,它指向; (3)一个函数,它返回; (4)一个指针,该指针指向; (5)一个有10个元素的数组,其类型为; (6)指针型,它指向; (7)int型数据。 因此a是一个函数指针变量,该函数返回的一个指针值又指向一个指针数组,该指针数组的元素指向整型量。 第七章:结构与联合 结构类型定义和结构变量说明   在实际问题中,一组数据往往具有不同的数据类型。例如, 在学生登记表中,姓名应为字符型;学号可为整型或字符型; 年龄应为整型;性别应为字符型;成绩可为整型或实型。 显然不能用一个数组来存放这一组数据。 因为数组中各元素的类型和长度都必须一致,以便于编译系统处理。为了解决这个问题,C语言中给出了另一种构造数据类型——“结构”。 它相当于其它高级语言中的记录。   “结构”是一种构造类型,它是由若干“成员”组成的。 每一个成员可以是一个基本数据类型或者又是一个构造类型。 结构既是一种“构造”而成的数据类型, 那么在说明和使用之前必须先定义它,也就是构造它。如同在说明和调用函数之前要先定义函数一样。 一、结构的定义 定义一个结构的一般形式为: struct 结构名 { 成员表列 }; 成员表由若干个成员组成, 每个成员都是该结构的一个组成部分。对每个成员也必须作类型说明,其形式为: 类型说明符 成员名; 成员名的命名应符合标识符的书写规定。例如: struct stu { int num; char name[20]; char sex; float score; };   在这个结构定义中,结构名为stu,该结构由4个成员组成。 第一个成员为num,整型变量;第二个成员为name,字符数组;第三个成员为sex,字符变量;第四个成员为score,实型变量。 应注意在括号后的分号是不可少的。结构定义之后,即可进行变量说明。 凡说明为结构stu的变量都由上述4个成员组成。由此可见, 结构是一种复杂的数据类型,是数目固定,类型不同的若干有序变量的集合。 二、结构类型变量的说明 说明结构变量有以下三种方法。以上面定义的stu为例来加以说明。 1. 先定义结构,再说明结构变量。如: struct stu { int num; char name[20]; char sex; float score; }; struct stu boy1,boy2; 说明了两个变量boy1和boy2为stu结构类型。也可以用宏定义使一个符号常量来表示一个结构类型,例如: #define STU struct stu STU { int num; char name[20]; char sex; float score; }; STU boy1,boy2; 2. 在定义结构类型的同时说明结构变量。例如: struct stu { int num; char name[20]; char sex; float score; }boy1,boy2; 3. 直接说明结构变量。例如: struct { int num; char name[20]; char sex; float score; }boy1,boy2;   第三种方法与第二种方法的区别在于第三种方法中省去了结构名,而直接给出结构变量。三种方法中说明的boy1,boy2变量都具有图7.1所示的结构。说明了boy1,boy2变量为stu类型后,即可向这两个变量中的各个成员赋值。在上述stu结构定义中,所有的成员都是基本数据类型或数组类型。成员也可以又是一个结构, 即构成了嵌套的结构。例如,图7.2给出了另一个数据结构。 按图7.2可给出以下结构定义: struct date{ int month; int day; int year; } struct{ int num; char name[20]; char sex; struct date birthday; float score; }boy1,boy2;   首先定义一个结构date,由month(月)、day(日)、year(年) 三个成员组成。 在定义并说明变量 boy1 和 boy2 时, 其中的成员birthday被说明为data结构类型。成员名可与程序中其它变量同名,互不干扰。结构变量成员的表示方法在程序中使用结构变量时, 往往不把它作为一个整体来使用。   在ANSI C中除了允许具有相同类型的结构变量相互赋值以外, 一般对结构变量的使用,包括赋值、输入、输出、 运算等都是通过结构变量的成员来实现的。   表示结构变量成员的一般形式是: 结构变量名.成员名 例如:boy1.num 即第一个人的学号 boy2.sex 即第二个人的性别 如果成员本身又是一个结构则必须逐级找到最低级的成员才能使用。例如:boy1.birthday.month 即第一个人出生的月份成员可以在程序中单独使用,与普通变量完全相同。 结构变量的赋值 前面已经介绍,结构变量的赋值就是给各成员赋值。 可用输入语句或赋值语句来完成。 [例7.1]给结构变量赋值并输出其值。 main(){ struct stu { int num; char *name; char sex; float score; } boy1,boy2; boy1.num=102; boy1.name="Zhang ping"; printf("input sex and score\n"); scanf("%c %f",&boy1.sex,&boy1.score); boy2=boy1; printf("Number=%d\nName=%s\n",boy2.num,boy2.name); printf("Sex=%c\nScore=%f\n",boy2.sex,boy2.score); } struct stu { int num; char *name; char sex; float score; }boy1,boy2; boy1.num=102; boy1.name="Zhang ping"; printf("input sex and score\n"); scanf("%c %f",&boy1.sex,&boy1.score); boy2=boy1; printf("Number=%d\nName=%s\n",boy2.num,boy2.name); printf("Sex=%c\nScore=%f\n",boy2.sex,boy2.score);   本程序中用赋值语句给num和name两个成员赋值,name是一个字符串指针变量。用scanf函数动态地输入sex和score成员值,然后把boy1的所有成员的值整体赋予boy2。最后分别输出boy2 的各个成员值。本例表示了结构变量的赋值、输入和输出的方法。 结构变量的初始化   如果结构变量是全局变量或为静态变量, 则可对它作初始化赋值。对局部或自动结构变量不能作初始化赋值。 [例7.2]外部结构变量初始化。 struct stu /*定义结构*/ { int num; char *name; char sex; float score; } boy2,boy1={102,"Zhang ping",'M',78.5}; main() { boy2=boy1; printf("Number=%d\nName=%s\n",boy2.num,boy2.name); printf("Sex=%c\nScore=%f\n",boy2.sex,boy2.score); } struct stu { int num; char *name; char sex; float score; }boy2,boy1={102,"Zhang ping",'M',78.5}; main() { boy2=boy1; …… } 本例中,boy2,boy1均被定义为外部结构变量,并对boy1作了初始化赋值。在main函数中,把boy1的值整体赋予boy2, 然后用两个printf语句输出boy2各成员的值。 [例7.3]静态结构变量初始化。 main() { static struct stu /*定义静态结构变量*/ { int num; char *name; char sex; float score; }boy2,boy1={102,"Zhang ping",'M',78.5}; boy2=boy1; printf("Number=%d\nName=%s\n",boy2.num,boy2.name); printf("Sex=%c\nScore=%f\n",boy2.sex,boy2.score); } static struct stu { int num; char *name; char sex; float score; }boy2,boy1={102,"Zhang ping",'M',78.5};   本例是把boy1,boy2都定义为静态局部的结构变量, 同样可以作初始化赋值。 结构数组 数组的元素也可以是结构类型的。 因此可以构成结构型数组。结构数组的每一个元素都是具有相同结构类型的下标结构变量。 在实际应用中,经常用结构数组来表示具有相同数据结构的一个群体。如一个班的学生档案,一个车间职工的工资表等。 结构数组的定义方法和结构变量相似,只需说明它为数组类型即可。例如: struct stu { int num; char *name; char sex; float score; }boy[5]; 定义了一个结构数组boy1,共有5个元素,boy[0]~boy[4]。每个数组元素都具有struct stu的结构形式。 对外部结构数组或静态结构数组可以作初始化赋值,例如: struct stu { int num; char *name; char sex; float score; }boy[5]={ {101,"Li ping","M",45}, {102,"Zhang ping","M",62.5}, {103,"He fang","F",92.5}, {104,"Cheng ling","F",87}, {105,"Wang ming","M",58}; } 当对全部元素作初始化赋值时,也可不给出数组长度。 [例7.4]计算学生的平均成绩和不及格的人数。 struct stu { int num; char *name; char sex; float score; }boy[5]={ {101,"Li ping",'M',45}, {102,"Zhang ping",'M',62.5}, {103,"He fang",'F',92.5}, {104,"Cheng ling",'F',87}, {105,"Wang ming",'M',58}, }; main() { int i,c=0; float ave,s=0; for(i=0;i<5;i++) { s+=boy[i].score; if(boy[i].score<60) c+=1; } printf("s=%f\n",s); ave=s/5; printf("average=%f\ncount=%d\n",ave,c); } 本例程序中定义了一个外部结构数组boy,共5个元素, 并作了初始化赋值。在main函数中用for语句逐个累加各元素的score 成员值存于s之中,如score的值小于60(不及格)即计数器C加1, 循环完毕后计算平均成绩,并输出全班总分,平均分及不及格人数。 [例7.5]建立同学通讯录 #include"stdio.h" #define NUM 3 struct mem { char name[20]; char phone[10]; }; main() { struct mem man[NUM]; int i; for(i=0;i成员名 例如: (*pstu).num或者: pstu->num 应该注意(*pstu)两侧的括号不可少, 因为成员符“.”的优先级高于“*”。如去掉括号写作*pstu.num则等效于*(pstu.num),这样,意义就完全不对了。 下面通过例子来说明结构指针变量的具体说明和使用方法。 [例7.6] struct stu { int num; char *name; char sex; float score; } boy1={102,"Zhang ping",'M',78.5},*pstu; main() { pstu=&boy1; printf("Number=%d\nName=%s\n",boy1.num,boy1.name); printf("Sex=%c\nScore=%f\n\n",boy1.sex,boy1.score); printf("Number=%d\nName=%s\n",(*pstu).num,(*pstu).name); printf("Sex=%c\nScore=%f\n\n",(*pstu).sex,(*pstu).score); printf("Number=%d\nName=%s\n",pstu->num,pstu->name); printf("Sex=%c\nScore=%f\n\n",pstu->sex,pstu->score); }   本例程序定义了一个结构stu,定义了stu类型结构变量boy1 并作了初始化赋值,还定义了一个指向stu类型结构的指针变量pstu。在main函数中,pstu被赋予boy1的地址,因此pstu指向boy1 。然后在printf语句内用三种形式输出boy1的各个成员值。 从运行结果可以看出: 结构变量.成员名 (*结构指针变量).成员名 结构指针变量->成员名   这三种用于表示结构成员的形式是完全等效的。结构数组指针变量结构指针变量可以指向一个结构数组, 这时结构指针变量的值是整个结构数组的首地址。 结构指针变量也可指向结构数组的一个元素,这时结构指针变量的值是该结构数组元素的首地址。设ps为指向结构数组的指针变量,则ps也指向该结构数组的0号元素,ps+1指向1号元素,ps+i则指向i号元素。 这与普通数组的情况是一致的。 [例7.7]用指针变量输出结构数组。 struct stu { int num; char *name; char sex; float score; }boy[5]={ {101,"Zhou ping",'M',45}, {102,"Zhang ping",'M',62.5}, {103,"Liou fang",'F',92.5}, {104,"Cheng ling",'F',87}, {105,"Wang ming",'M',58}, }; main() { struct stu *ps; printf("No\tName\t\t\tSex\tScore\t\n"); for(ps=boy;psnum,ps->name,ps->sex,ps-> score); }   在程序中,定义了stu结构类型的外部数组boy 并作了初始化赋值。在main函数内定义ps为指向stu类型的指针。在循环语句for的表达式1中,ps被赋予boy的首地址,然后循环5次,输出boy数组中各成员值。 应该注意的是, 一个结构指针变量虽然可以用来访问结构变量或结构数组元素的成员,但是,不能使它指向一个成员。 也就是说不允许取一个成员的地址来赋予它。因此,下面的赋值是错误的。 ps=&boy[1].sex;而只能是:ps=boy;(赋予数组首地址) 或者是: ps=&boy[0];(赋予0号元素首地址) 结构指针变量作函数参数   在ANSI C标准中允许用结构变量作函数参数进行整体传送。 但是这种传送要将全部成员逐个传送, 特别是成员为数组时将会使传送的时间和空间开销很大,严重地降低了程序的效率。 因此最好的办法就是使用指针,即用指针变量作函数参数进行传送。 这时由实参传向形参的只是地址,从而减少了时间和空间的开销。 [例7.8]题目与例7.4相同,计算一组学生的平均成绩和不及格人数。 用结构指针变量作函数参数编程。 struct stu { int num; char *name; char sex; float score;}boy[5]={ {101,"Li ping",'M',45}, {102,"Zhang ping",'M',62.5}, {103,"He fang",'F',92.5}, {104,"Cheng ling",'F',87}, {105,"Wang ming",'M',58}, }; main() { struct stu *ps; void ave(struct stu *ps); ps=boy; ave(ps); } void ave(struct stu *ps) { int c=0,i; float ave,s=0; for(i=0;i<5;i++,ps++) { s+=ps->score; if(ps->score<60) c+=1; } printf("s=%f\n",s); ave=s/5; printf("average=%f\ncount=%d\n",ave,c); }   本程序中定义了函数ave,其形参为结构指针变量ps。boy 被定义为外部结构数组,因此在整个源程序中有效。在main 函数中定义说明了结构指针变量ps,并把boy的首地址赋予它,使ps指向boy 数组。然后以ps作实参调用函数ave。在函数ave 中完成计算平均成绩和统计不及格人数的工作并输出结果。与例7.4程序相比,由于本程序全部采用指针变量作运算和处理,故速度更快,程序效率更高。. topoic=动态存储分配   在数组一章中,曾介绍过数组的长度是预先定义好的, 在整个程序中固定不变。C语言中不允许动态数组类型。例如: int n;scanf("%d",&n);int a[n]; 用变量表示长度,想对数组的大小作动态说明, 这是错误的。但是在实际的编程中,往往会发生这种情况, 即所需的内存空间取决于实际输入的数据,而无法预先确定。对于这种问题, 用数组的办法很难解决。为了解决上述问题,C语言提供了一些内存管理函数,这些内存管理函数可以按需要动态地分配内存空间, 也可把不再使用的空间回收待用,为有效地利用内存资源提供了手段。 常用的内存管理函数有以下三个: 1.分配内存空间函数malloc 调用形式: (类型说明符*) malloc (size) 功能:在内存的动态存储区中分配一块长度为"size" 字节的连续区域。函数的返回值为该区域的首地址。 “类型说明符”表示把该区域用于何种数据类型。(类型说明符*)表示把返回值强制转换为该类型指针。“size”是一个无符号数。例如: pc=(char *) malloc (100); 表示分配100个字节的内存空间,并强制转换为字符数组类型, 函数的返回值为指向该字符数组的指针, 把该指针赋予指针变量pc。 2.分配内存空间函数 calloc calloc 也用于分配内存空间。调用形式: (类型说明符*)calloc(n,size) 功能:在内存动态存储区中分配n块长度为“size”字节的连续区域。函数的返回值为该区域的首地址。(类型说明符*)用于强制类型转换。calloc函数与malloc 函数的区别仅在于一次可以分配n块区域。例如: ps=(struet stu*) calloc(2,sizeof (struct stu)); 其中的sizeof(struct stu)是求stu的结构长度。因此该语句的意思是:按stu的长度分配2块连续区域,强制转换为stu类型,并把其首地址赋予指针变量ps。 3.释放内存空间函数free 调用形式: free(void*ptr); 功能:释放ptr所指向的一块内存空间,ptr 是一个任意类型的指针变量,它指向被释放区域的首地址。被释放区应是由malloc或calloc函数所分配的区域:[例7.9]分配一块区域,输入一个学生数据。 main() { struct stu { int num; char *name; char sex; float score; } *ps; ps=(struct stu*)malloc(sizeof(struct stu)); ps->num=102; ps->name="Zhang ping"; ps->sex='M'; ps->score=62.5; printf("Number=%d\nName=%s\n",ps->num,ps->name); printf("Sex=%c\nScore=%f\n",ps->sex,ps->score); free(ps); }   本例中,定义了结构stu,定义了stu类型指针变量ps。 然后分配一块stu大内存区,并把首地址赋予ps,使ps指向该区域。再以ps为指向结构的指针变量对各成员赋值,并用printf 输出各成员值。最后用free函数释放ps指向的内存空间。 整个程序包含了申请内存空间、使用内存空间、释放内存空间三个步骤, 实现存储空间的动态分配。链表的概念在例7.9中采用了动态分配的办法为一个结构分配内存空间。每一次分配一块空间可用来存放一个学生的数据, 我们可称之为一个结点。有多少个学生就应该申请分配多少块内存空间, 也就是说要建立多少个结点。当然用结构数组也可以完成上述工作, 但如果预先不能准确把握学生人数,也就无法确定数组大小。 而且当学生留级、退学之后也不能把该元素占用的空间从数组中释放出来。 用动态存储的方法可以很好地解决这些问题。 有一个学生就分配一个结点,无须预先确定学生的准确人数,某学生退学, 可删去该结点,并释放该结点占用的存储空间。从而节约了宝贵的内存资源。 另一方面,用数组的方法必须占用一块连续的内存区域。 而使用动态分配时,每个结点之间可以是不连续的(结点内是连续的)。 结点之间的联系可以用指针实现。 即在结点结构中定义一个成员项用来存放下一结点的首地址,这个用于存放地址的成员,常把它称为指针域。可在第一个结点的指针域内存入第二个结点的首地址, 在第二个结点的指针域内又存放第三个结点的首地址, 如此串连下去直到最后一个结点。最后一个结点因无后续结点连接,其指针域可赋为0。这样一种连接方式,在数据结构中称为“链表”。图7.3为链表的示意图。   在图7.3中,第0个结点称为头结点, 它存放有第一个结点的首地址,它没有数据,只是一个指针变量。 以下的每个结点都分为两个域,一个是数据域,存放各种实际的数据,如学号num,姓名name,性别sex和成绩score等。另一个域为指针域, 存放下一结点的首地址。链表中的每一个结点都是同一种结构类型。例如, 一个存放学生学号和成绩的结点应为以下结构: struct stu { int num; int score; struct stu *next; }   前两个成员项组成数据域,后一个成员项next构成指针域, 它是一个指向stu类型结构的指针变量。链表的基本操作对链表的主要操作有以下几种: 1.建立链表; 2.结构的查找与输出; 3.插入一个结点; 4.删除一个结点; 下面通过例题来说明这些操作。 [例7.10]建立一个三个结点的链表,存放学生数据。 为简单起见, 我们假定学生数据结构中只有学号和年龄两项。 可编写一个建立链表的函数creat。程序如下: #define NULL 0 #define TYPE struct stu #define LEN sizeof (struct stu) struct stu { int num; int age; struct stu *next; }; TYPE *creat(int n) { struct stu *head,*pf,*pb; int i; for(i=0;inum,&pb->age); if(i==0) pf=head=pb; else pf->next=pb; pb->next=NULL; pf=pb; } return(head); }   在函数外首先用宏定义对三个符号常量作了定义。这里用TYPE表示struct stu,用LEN表示sizeof(struct stu)主要的目的是为了在以下程序内减少书写并使阅读更加方便。结构stu定义为外部类型,程序中的各个函数均可使用该定义。   creat函数用于建立一个有n个结点的链表,它是一个指针函数,它返回的指针指向stu结构。在creat函数内定义了三个stu结构的指针变量。head为头指针,pf 为指向两相邻结点的前一结点的指针变量。pb为后一结点的指针变量。在for语句内,用malloc函数建立长度与stu长度相等的空间作为一结点,首地址赋予pb。然后输入结点数据。如果当前结点为第一结点(i==0),则把pb值 (该结点指针)赋予head和pf。如非第一结点,则把pb值赋予pf 所指结点的指针域成员next。而pb所指结点为当前的最后结点,其指针域赋NULL。 再把pb值赋予pf以作下一次循环准备。   creat函数的形参n,表示所建链表的结点数,作为for语句的循环次数。图7.4表示了creat函数的执行过程。 [例7.11]写一个函数,在链表中按学号查找该结点。 TYPE * search (TYPE *head,int n) { TYPE *p; int i; p=head; while (p->num!=n && p->next!=NULL) p=p->next; /* 不是要找的结点后移一步*/ if (p->num==n) return (p); if (p->num!=n&& p->next==NULL) printf ("Node %d has not been found!\n",n }   本函数中使用的符号常量TYPE与例7.10的宏定义相同,等于struct stu。函数有两个形参,head是指向链表的指针变量,n为要查找的学号。进入while语句,逐个检查结点的num成员是否等于n,如果不等于n且指针域不等于NULL(不是最后结点)则后移一个结点,继续循环。如找到该结点则返回结点指针。 如循环结束仍未找到该结点则输出“未找到”的提示信息。 [例7.12]写一个函数,删除链表中的指定结点。删除一个结点有两种情况: 1. 被删除结点是第一个结点。这种情况只需使head指向第二个结点即可。即head=pb->next。其过程如图7.5所示。 2. 被删结点不是第一个结点,这种情况使被删结点的前一结点指向被删结点的后一结点即可。即pf->next=pb->next。其过程如图7.6所示。 函数编程如下: TYPE * delete(TYPE * head,int num) { TYPE *pf,*pb; if(head==NULL) /*如为空表, 输出提示信息*/ { printf("\nempty list!\n"); goto end;} pb=head; while (pb->num!=num && pb->next!=NULL) /*当不是要删除的结点,而且也不是最后一个结点时,继续循环*/ {pf=pb;pb=pb->next;}/*pf指向当前结点,pb指向下一结点*/ if(pb->num==num) {if(pb==head) head=pb->next; /*如找到被删结点,且为第一结点,则使head指向第二个结点, 否则使pf所指结点的指针指向下一结点*/ else pf->next=pb->next; free(pb); printf("The node is deleted\n");} else printf("The node not been foud!\n"); end: return head; }   函数有两个形参,head为指向链表第一结点的指针变量,num删结点的学号。 首先判断链表是否为空,为空则不可能有被删结点。若不为空,则使pb指针指向链表的第一个结点。进入while语句后逐个查找被删结点。找到被删结点之后再看是否为第一结点,若是则使head指向第二结点(即把第一结点从链中删去),否则使被删结点的前一结点(pf所指)指向被删结点的后一结点(被删结点的指针域所指)。如若循环结束未找到要删的结点, 则输出“末找到”的提示信息。最后返回head值。 [例7.13]写一个函数,在链表中指定位置插入一个结点。在一个链表的指定位置插入结点, 要求链表本身必须是已按某种规律排好序的。例如,在学生数据链表中, 要求学号顺序插入一个结点。设被插结点的指针为pi。 可在三种不同情况下插入。 1. 原表是空表,只需使head指向被插结点即可。见图7.7(a) 2. 被插结点值最小,应插入第一结点之前。这种情况下使head指向被插结点,被插结点的指针域指向原来的第一结点则可。即:pi->next=pb; head=pi; 见图7.7(b) 3. 在其它位置插入,见图7.7(c)。这种情况下,使插入位置的前一结点的指针域指向被插结点,使被插结点的指针域指向插入位置的后一结点。即为:pi->next=pb;pf->next=pi; 4. 在表末插入,见图7.7(d)。这种情况下使原表末结点指针域指向被插结点,被插结点指针域置为NULL。即: pb->next=pi; pi->next=NULL; TYPE * insert(TYPE * head,TYPE *pi) { TYPE *pf,*pb; pb=head; if(head==NULL) /*空表插入*/ (head=pi; pi->next=NULL;} else { while((pi->num>pb->num)&&(pb->next!=NULL)) {pf=pb; pb=pb->next; }/*找插入位置*/ if(pi->num<=pb->num) {if(head==pb)head=pi;/*在第一结点之前插入*/ else pf->next=pi;/*在其它位置插入*/ pi->next=pb; } else {pb->next=pi; pi->next=NULL;} /*在表末插入*/ } return head;}   本函数有两个形参均为指针变量,head指向链表,pi 指向被插结点。函数中首先判断链表是否为空,为空则使head指向被插结点。表若不空,则用while语句循环查找插入位置。找到之后再判断是否在第一结点之前插入,若是则使head 指向被插结点被插结点指针域指向原第一结点,否则在其它位置插入, 若插入的结点大于表中所有结点,则在表末插入。本函数返回一个指针, 是链表的头指针。 当插入的位置在第一个结点之前时, 插入的新结点成为链表的第一个结点,因此head的值也有了改变, 故需要把这个指针返回主调函数。 [例7.14]将以上建立链表,删除结点,插入结点的函数组织在一起,再建一个输出全部结点的函数,然后用main函数调用它们。 #define NULL 0 #define TYPE struct stu #define LEN sizeof(struct stu) struct stu { int num; int age; struct stu *next; }; TYPE * creat(int n) { struct stu *head,*pf,*pb; int i; for(i=0;inum,&pb->age); if(i==0) pf=head=pb; else pf->next=pb; pb->next=NULL; pf=pb; } return(head); } TYPE * delete(TYPE * head,int num) { TYPE *pf,*pb; if(head==NULL) { printf("\nempty list!\n"); goto end;} pb=head; while (pb->num!=num && pb->next!=NULL) {pf=pb;pb=pb->next;} if(pb->num==num) { if(pb==head) head=pb->next; else pf->next=pb->next; printf("The node is deleted\n"); } else free(pb); printf("The node not been found!\n"); end: return head; } TYPE * insert(TYPE * head,TYPE * pi) { TYPE *pb ,*pf; pb=head; if(head==NULL) { head=pi; pi->next=NULL; } else { while((pi->num>pb->num)&&(pb->next!=NULL)) { pf=pb; pb=pb->next; } if(pi->num<=pb->num) { if(head==pb) head=pi; else pf->next=pi; pi->next=pb; } else { pb->next=pi; pi->next=NULL; } } return head; } void print(TYPE * head) { printf("Number\t\tAge\n"); while(head!=NULL) { printf("%d\t\t%d\n",head->num,head->age); head=head->next; } } main() { TYPE * head,*pnum; int n,num; printf("input number of node: "); scanf("%d",&n); head=creat(n); print(head); printf("Input the deleted number: "); scanf("%d",&num); head=delete(head,num); print(head); printf("Input the inserted number and age: "); pnum=(TYPE *)malloc(LEN); scanf("%d%d",&pnum->num,&pnum->age); head=insert(head,pnum); print(head); }   本例中,print函数用于输出链表中各个结点数据域值。函数的形参head的初值指向链表第一个结点。在while语句中,输出结点值后,head值被改变,指向下一结点。若保留头指针head, 则应另设一个指针变量,把head值赋予它,再用它来替代head。在main函数中,n为建立结点的数目, num为待删结点的数据域值;head为指向链表的头指针,pnum为指向待插结点的指针。 main函数中各行的意义是: 第六行输入所建链表的结点数; 第七行调creat函数建立链表并把头指针返回给head; 第八行调print函数输出链表; 第十行输入待删结点的学号; 第十一行调delete函数删除一个结点; 第十二行调print函数输出链表; 第十四行调malloc函数分配一个结点的内存空间, 并把其地址赋予pnum; 第十五行输入待插入结点的数据域值; 第十六行调insert函数插入pnum所指的结点; 第十七行再次调print函数输出链表。   从运行结果看,首先建立起3个结点的链表,并输出其值;再删103号结点,只剩下105,108号结点;又输入106号结点数据, 插入后链表中的结点为105,106,108。联合“联合”也是一种构造类型的数据结构。 在一个“联合”内可以定义多种不同的数据类型, 一个被说明为该“联合”类型的变量中,允许装入该“联合”所定义的任何一种数据。 这在前面的各种数据类型中都是办不到的。例如, 定义为整型的变量只能装入整型数据,定义为实型的变量只能赋予实型数据。   在实际问题中有很多这样的例子。 例如在学校的教师和学生中填写以下表格: 姓 名 年 龄 职 业 单位 “职业”一项可分为“教师”和“学生”两类。 对“单位”一项学生应填入班级编号,教师应填入某系某教研室。 班级可用整型量表示,教研室只能用字符类型。 要求把这两种类型不同的数据都填入“单位”这个变量中, 就必须把“单位”定义为包含整型和字符型数组这两种类型的“联合”。   “联合”与“结构”有一些相似之处。但两者有本质上的不同。在结构中各成员有各自的内存空间, 一个结构变量的总长度是各成员长度之和。而在“联合”中,各成员共享一段内存空间, 一个联合变量的长度等于各成员中最长的长度。应该说明的是, 这里所谓的共享不是指把多个成员同时装入一个联合变量内, 而是指该联合变量可被赋予任一成员值,但每次只能赋一种值, 赋入新值则冲去旧值。如前面介绍的“单位”变量, 如定义为一个可装入“班级”或“教研室”的联合后,就允许赋予整型值(班级)或字符串(教研室)。要么赋予整型值,要么赋予字符串,不能把两者同时赋予它。联合类型的定义和联合变量的说明一个联合类型必须经过定义之后, 才能把变量说明为该联合类型。 一、联合的定义 定义一个联合类型的一般形式为: union 联合名 { 成员表 }; 成员表中含有若干成员,成员的一般形式为: 类型说明符 成员名 成员名的命名应符合标识符的规定。 例如: union perdata { int class; char office[10]; };   定义了一个名为perdata的联合类型,它含有两个成员,一个为整型,成员名为class;另一个为字符数组,数组名为office。联合定义之后,即可进行联合变量说明,被说明为perdata类型的变量,可以存放整型量class或存放字符数组office。 二、联合变量的说明   联合变量的说明和结构变量的说明方式相同, 也有三种形式。即先定义,再说明;定义同时说明和直接说明。以perdata类型为例,说明如下: union perdata { int class; char officae[10]; }; union perdata a,b; /*说明a,b为perdata类型*/ 或者可同时说明为: union perdata { int class; char office[10]; }a,b;或直接说明为: union { int class; char office[10]; }a,b 经说明后的a,b变量均为perdata类型。 它们的内存分配示意图如图7—8所示。a,b变量的长度应等于 perdata 的成员中最长的长度, 即等于 office数组的长度,共10个字节。从图中可见,a,b变量如赋予整型值时,只使用了2个字节,而赋予字符数组时,可用10个字节。 联合变量的赋值和使用   对联合变量的赋值,使用都只能是对变量的成员进行。 联合变量的成员表示为: 联合变量名.成员名 例如,a被说明为perdata类型的变量之后,可使用 a.class a.office 不允许只用联合变量名作赋值或其它操作。 也不允许对联合变量作初始化赋值,赋值只能在程序中进行。还要再强调说明的是,一个联合变量, 每次只能赋予一个成员值。换句话说,一个联合变量的值就是联合变员的某一个成员值。 [例7.15]设有一个教师与学生通用的表格,教师数据有姓名,年龄,职业,教研室四项。学生有姓名,年龄,职业,班级四项。 编程输入人员数据, 再以表格输出。 main() { struct { char name[10]; int age; char job; union { int class; char office[10]; } depa; }body[2]; int n,i; for(i=0;i<2;i++) { printf("input name,age,job and department\n"); scanf("%s %d %c",body[i].name,&body[i].age,&body[i].job); if(body[i].job=='s') scanf("%d",&body[i].depa.class); else scanf("%s",body[i].depa.office); } printf("name\tage job class/office\n"); for(i=0;i<2;i++) { if(body[i].job=='s') printf("%s\t%3d %3c %d\n",body[i].name,body[i].age ,body[i].job,body[i].depa.class); else printf("%s\t%3d %3c %s\n",body[i].name,body[i].age, body[i].job,body[i].depa.office); } }   本例程序用一个结构数组body来存放人员数据, 该结构共有四个成员。其中成员项depa是一个联合类型, 这个联合又由两个成员组成,一个为整型量class,一个为字符数组office。在程序的第一个for语句中,输入人员的各项数据,先输入结构的前三个成员name,age和job,然后判别job成员项,如为"s"则对联合depa·class输入(对学生赋班级编号)否则对depa·office输入(对教师赋教研组名)。   在用scanf语句输入时要注意,凡为数组类型的成员,无论是结构成员还是联合成员,在该项前不能再加"&"运算符。如程序第18行中 body[i].name是一个数组类型,第22行中的body[i].depa.office也是数组类型,因此在这两项之间不能加"&"运算符。程序中的第二个for语句用于输出各成员项的值: 本章小结 1. 结构和联合是两种构造类型数据,是用户定义新数据类型的重要手段。结构和联合有很多的相似之处,它们都由成员组成。成员可以具有不同的数据类型。成员的表示方法相同。都可用三种方式作变量说明。 2. 在结构中,各成员都占有自己的内存空间,它们是同时存在的。一个结构变量的总长度等于所有成员长度之和。在联合中,所有成员不能同时占用它的内存空间,它们不能同时存在。联合变量的长度等于最长的成员的长度。 3. “.”是成员运算符,可用它表示成员项,成员还可用“->”运算符来表示。 4. 结构变量可以作为函数参数,函数也可返回指向结构的指针变量。而联合变量不能作为函数参数,函数也不能返回指向联合的指针变量。但可以使用指向联合变量的指针,也可使用联合数组。 5. 结构定义允许嵌套,结构中也可用联合作为成员,形成结构和联合的嵌套。 6. 链表是一种重要的数据结构,它便于实现动态的存储分配。本章介绍是单向链表,还可组成双向链表,循环链表等 第八章:枚举,位运算 枚举   在实际问题中, 有些变量的取值被限定在一个有限的范围内。例如,一个星期内只有七天,一年只有十二个月, 一个班每周有六门课程等等。如果把这些量说明为整型, 字符型或其它类型显然是不妥当的。 为此,C语言提供了一种称为“枚举”的类型。在“枚举”类型的定义中列举出所有可能的取值, 被说明为该“枚举”类型的变量取值不能超过定义的范围。应该说明的是, 枚举类型是一种基本数据类型,而不是一种构造类型, 因为它不能再分解为任何基本类型。 枚举类型的定义和枚举变量的说明 一、枚举的定义枚举类型定义的一般形式为: enum 枚举名 { 枚举值表 }; 在枚举值表中应罗列出所有可用值。这些值也称为枚举元素。 例如: enum weekday { sun,mou,tue,wed,thu,fri,sat }; 该枚举名为weekday,枚举值共有7个,即一周中的七天。 凡被说明为weekday类型变量的取值只能是七天中的某一天。 二、枚举变量的说明 如同结构和联合一样,枚举变量也可用不同的方式说明, 即先定义后说明,同时定义说明或直接说明。设有变量a,b,c被说明为上述的weekday,可采用下述任一种方式: enum weekday { ...... }; enum weekday a,b,c;或者为: enum weekday { ...... }a,b,c;或者为: enum { ...... }a,b,c; 枚举类型变量的赋值和使用 枚举类型在使用中有以下规定: 1. 枚举值是常量,不是变量。不能在程序中用赋值语句再对它赋值。例如对枚举weekday的元素再作以下赋值: sun=5;mon=2;sun=mon; 都是错误的。 2. 枚举元素本身由系统定义了一个表示序号的数值,从0 开始顺序定义为0,1,2…。如在weekday中,sun值为0,mon值为1, …,sat值为6。 main(){ enum weekday { sun,mon,tue,wed,thu,fri,sat } a,b,c; a=sun; b=mon; c=tue; printf("%d,%d,%d",a,b,c); } 3. 只能把枚举值赋予枚举变量,不能把元素的数值直接赋予枚举变量。如: a=sum;b=mon; 是正确的。而: a=0;b=1; 是错误的。如一定要把数值赋予枚举变量,则必须用强制类型转换,如: a=(enum weekday)2;其意义是将顺序号为2的枚举元素赋予枚举变量a,相当于: a=tue; 还应该说明的是枚举元素不是字符常量也不是字符串常量, 使用时不要加单、双引号。 main(){ enum body { a,b,c,d } month[31],j; int i; j=a; for(i=1;i<=30;i++){ month[i]=j; j++; if (j>d) j=a; } for(i=1;i<=30;i++){ switch(month[i]) { case a:printf(" %2d %c\t",i,'a'); break; case b:printf(" %2d %c\t",i,'b'); break; case c:printf(" %2d %c\t",i,'c'); break; case d:printf(" %2d %c\t",i,'d'); break; default:break; } } printf("\n"); } 位运算   前面介绍的各种运算都是以字节作为最基本位进行的。 但在很多系统程序中常要求在位(bit)一级进行运算或处理。C语言提供了位运算的功能, 这使得C语言也能像汇编语言一样用来编写系统程序。 一、位运算符C语言提供了六种位运算符: & 按位与 | 按位或 ^ 按位异或 ~ 取反 << 左移 >> 右移 1. 按位与运算 按位与运算符"&"是双目运算符。其功能是参与运算的两数各对应的二进位相与。只有对应的两个二进位均为1时,结果位才为1 ,否则为0。参与运算的数以补码方式出现。 例如:9&5可写算式如下: 00001001 (9的二进制补码)&00000101 (5的二进制补码) 00000001 (1的二进制补码)可见9&5=1。   按位与运算通常用来对某些位清0或保留某些位。例如把a 的高八位清 0 , 保留低八位, 可作 a&255 运算 ( 255 的二进制数为0000000011111111)。 main(){ int a=9,b=5,c; c=a&b; printf("a=%d\nb=%d\nc=%d\n",a,b,c); } 2. 按位或运算 按位或运算符“|”是双目运算符。其功能是参与运算的两数各对应的二进位相或。只要对应的二个二进位有一个为1时,结果位就为1。参与运算的两个数均以补码出现。 例如:9|5可写算式如下: 00001001|00000101 00001101 (十进制为13)可见9|5=13 main(){ int a=9,b=5,c; c=a|b; printf("a=%d\nb=%d\nc=%d\n",a,b,c); } 3. 按位异或运算 按位异或运算符“^”是双目运算符。其功能是参与运算的两数各对应的二进位相异或,当两对应的二进位相异时,结果为1。参与运算数仍以补码出现,例如9^5可写成算式如下: 00001001^00000101 00001100 (十进制为12) main(){ int a=9; a=a^15; printf("a=%d\n",a); } 4. 求反运算 求反运算符~为单目运算符,具有右结合性。 其功能是对参与运算的数的各二进位按位求反。例如~9的运算为: ~(0000000000001001)结果为:1111111111110110 5. 左移运算 左移运算符“<<”是双目运算符。其功能把“<< ”左边的运算数的各二进位全部左移若干位,由“<<”右边的数指定移动的位数, 高位丢弃,低位补0。例如: a<<4 指把a的各二进位向左移动4位。如a=00000011(十进制3),左移4位后为00110000(十进制48)。6. 右移运算 右移运算符“>>”是双目运算符。其功能是把“>> ”左边的运算数的各二进位全部右移若干位,“>>”右边的数指定移动的位数。 例如:设 a=15,a>>2 表示把000001111右移为00000011(十进制3)。 应该说明的是,对于有符号数,在右移时,符号位将随同移动。当为正数时, 最高位补0,而为负数时,符号位为1,最高位是补0或是补1 取决于编译系统的规定。Turbo C和很多系统规定为补1。 main(){ unsigned a,b; printf("input a number: "); scanf("%d",&a); b=a>>5; b=b&15; printf("a=%d\tb=%d\n",a,b); } 请再看一例! main(){ char a='a',b='b'; int p,c,d; p=a; p=(p<<8)|b; d=p&0xff; c=(p&0xff00)>>8; printf("a=%d\nb=%d\nc=%d\nd=%d\n",a,b,c,d); } 位域 有些信息在存储时,并不需要占用一个完整的字节, 而只需占几个或一个二进制位。例如在存放一个开关量时,只有0和1 两种状态, 用一位二进位即可。为了节省存储空间,并使处理简便,C语言又提供了一种数据结构,称为“位域”或“位段”。所谓“位域”是把一个字节中的二进位划分为几个不同的区域, 并说明每个区域的位数。每个域有一个域名,允许在程序中按域名进行操作。 这样就可以把几个不同的对象用一个字节的二进制位域来表示。一、位域的定义和位域变量的说明位域定义与结构定义相仿,其形式为: struct 位域结构名 { 位域列表 }; 其中位域列表的形式为: 类型说明符 位域名:位域长度 例如: struct bs { int a:8; int b:2; int c:6; }; 位域变量的说明与结构变量说明的方式相同。 可采用先定义后说明,同时定义说明或者直接说明这三种方式。例如: struct bs { int a:8; int b:2; int c:6; }data; 说明data为bs变量,共占两个字节。其中位域a占8位,位域b占2位,位域c占6位。对于位域的定义尚有以下几点说明: 1. 一个位域必须存储在同一个字节中,不能跨两个字节。如一个字节所剩空间不够存放另一位域时,应从下一单元起存放该位域。也可以有意使某位域从下一单元开始。例如: struct bs { unsigned a:4 unsigned :0 /*空域*/ unsigned b:4 /*从下一单元开始存放*/ unsigned c:4 } 在这个位域定义中,a占第一字节的4位,后4位填0表示不使用,b从第二字节开始,占用4位,c占用4位。 2. 由于位域不允许跨两个字节,因此位域的长度不能大于一个字节的长度,也就是说不能超过8位二进位。 3. 位域可以无位域名,这时它只用来作填充或调整位置。无名的位域是不能使用的。例如: struct k { int a:1 int :2 /*该2位不能使用*/ int b:3 int c:2 }; 从以上分析可以看出,位域在本质上就是一种结构类型, 不过其成员是按二进位分配的。 二、位域的使用位域的使用和结构成员的使用相同,其一般形式为: 位域变量名·位域名 位域允许用各种格式输出。 main(){ struct bs { unsigned a:1; unsigned b:3; unsigned c:4; } bit,*pbit; bit.a=1; bit.b=7; bit.c=15; printf("%d,%d,%d\n",bit.a,bit.b,bit.c); pbit=&bit; pbit->a=0; pbit->b&=3; pbit->c|=1; printf("%d,%d,%d\n",pbit->a,pbit->b,pbit->c); } 上例程序中定义了位域结构bs,三个位域为a,b,c。说明了bs类型的变量bit和指向bs类型的指针变量pbit。这表示位域也是可以使用指针的。 程序的9、10、11三行分别给三个位域赋值。( 应注意赋值不能超过该位域的允许范围)程序第12行以整型量格式输出三个域的内容。第13行把位域变量bit的地址送给指针变量pbit。第14行用指针方式给位域a重新赋值,赋为0。第15行使用了复合的位运算符"&=", 该行相当于: pbit->b=pbit->b&3位域b中原有值为7,与3作按位与运算的结果为3(111&011=011,十进制值为3)。同样,程序第16行中使用了复合位运算"|=", 相当于: pbit->c=pbit->c|1其结果为15。程序第17行用指针方式输出了这三个域的值。 类型定义符typedef C语言不仅提供了丰富的数据类型,而且还允许由用户自己定义类型说明符,也就是说允许由用户为数据类型取“别名”。 类型定义符typedef即可用来完成此功能。例如,有整型量a,b,其说明如下: int aa,b; 其中int是整型变量的类型说明符。int的完整写法为integer, 为了增加程序的可读性,可把整型说明符用typedef定义为: typedef int INTEGER 这以后就可用INTEGER来代替int作整型变量的类型说明了。 例如: INTEGER a,b;它等效于: int a,b; 用typedef定义数组、指针、结构等类型将带来很大的方便,不仅使程序书写简单而且使意义更为明确,因而增强了可读性。例如: typedef char NAME[20]; 表示NAME是字符数组类型,数组长度为20。 然后可用NAME 说明变量,如: NAME a1,a2,s1,s2;完全等效于: char a1[20],a2[20],s1[20],s2[20] 又如: typedef struct stu{ char name[20]; int age; char sex; } STU; 定义STU表示stu的结构类型,然后可用STU来说明结构变量: STU body1,body2; typedef定义的一般形式为: typedef 原类型名 新类型名 其中原类型名中含有定义部分,新类型名一般用大写表示, 以 便于区别。在有时也可用宏定义来代替typedef的功能,但是宏定义是由预处理完成的,而typedef则是在编译时完成的,后者更为灵活方便。 本章小结 1. 枚举是一种基本数据类型。枚举变量的取值是有限的,枚举元素是常量,不是变量。 2. 枚举变量通常由赋值语句赋值,而不由动态输入赋值。枚举元素虽可由系统或用户定义一个顺序值,但枚举元素和整数并不相同,它们属于不同的类型。因此,也不能用printf语句来输出元素值(可输出顺序值)。 3. 位运算是C语言的一种特殊运算功能, 它是以二进制位为单位进行运算的。位运算符只有逻辑运算和移位运算两类。位运算符可以与赋值符一起组成复合赋值符。如&=,|=,^=,>>=,<<=等。 4. 利用位运算可以完成汇编语言的某些功能,如置位,位清零,移位等。还可进行数据的压缩存储和并行运算。 5. 位域在本质上也是结构类型,不过它的成员按二进制位分配内存。其定义、说明及使用的方式都与结构相同。 6. 位域提供了一种手段,使得可在高级语言中实现数据的压缩,节省了存储空间,同时也提高了程序的效率。 7. 类型定义typedef 向用户提供了一种自定义类型说明符的手段,照顾了用户编程使用词汇的习惯,又增加了程序的可读性。 第九章:预处理 预处理 概述   在前面各章中,已多次使用过以“#”号开头的预处理命令。如包含命令# include,宏定义命令# define等。在源程序中这些命令都放在函数之外, 而且一般都放在源文件的前面,它们称为预处理部分。   所谓预处理是指在进行编译的第一遍扫描(词法扫描和语法分析)之前所作的工作。预处理是C语言的一个重要功能, 它由预处理程序负责完成。当对一个源文件进行编译时, 系统将自动引用预处理程序对源程序中的预处理部分作处理, 处理完毕自动进入对源程序的编译。   C语言提供了多种预处理功能,如宏定义、文件包含、 条件编译等。合理地使用预处理功能编写的程序便于阅读、修改、 移植和调试,也有利于模块化程序设计。本章介绍常用的几种预处理功能。 宏定义   在C语言源程序中允许用一个标识符来表示一个字符串, 称为“宏”。被定义为“宏”的标识符称为“宏名”。在编译预处理时,对程序中所有出现的“宏名”,都用宏定义中的字符串去代换, 这称为“宏代换”或“宏展开”。   宏定义是由源程序中的宏定义命令完成的。 宏代换是由预处理程序自动完成的。在C语言中,“宏”分为有参数和无参数两种。 下面分别讨论这两种“宏”的定义和调用。 无参宏定义   无参宏的宏名后不带参数。其定义的一般形式为: #define 标识符 字符串 其中的“#”表示这是一条预处理命令。凡是以“#”开头的均为预处理命令。“define”为宏定义命令。 “标识符”为所定义的宏名。“字符串”可以是常数、表达式、格式串等。在前面介绍过的符号常量的定义就是一种无参宏定义。 此外,常对程序中反复使用的表达式进行宏定义。例如: # define M (y*y+3*y) 定义M表达式(y*y+3*y)。在编写源程序时,所有的(y*y+3*y)都可由M代替,而对源程序作编译时,将先由预处理程序进行宏代换,即用(y*y+3*y)表达式去置换所有的宏名M,然后再进行编译。 #define M (y*y+3*y) main(){ int s,y; printf("input a number: "); scanf("%d",&y); s=3*M+4*M+5*M; printf("s=%d\n",s); }   上例程序中首先进行宏定义,定义M表达式(y*y+3*y),在s= 3*M+4*M+5* M中作了宏调用。在预处理时经宏展开后该语句变为:s=3*(y*y+3*y)+4(y*y+3*y)+5(y*y+3*y);但要注意的是,在宏定义中表达式(y*y+3*y)两边的括号不能少。否则会发生错误。   当作以下定义后: #difine M y*y+3*y在宏展开时将得到下述语句: s=3*y*y+3*y+4*y*y+3*y+5*y*y+3*y;这相当于; 3y2+3y+4y2+3y+5y2+3y;显然与原题意要求不符。计算结果当然是错误的。 因此在作宏定义时必须十分注意。应保证在宏代换之后不发生错误。对于宏定义还要说明以下几点: 1. 宏定义是用宏名来表示一个字符串,在宏展开时又以该字符串取代宏名,这只是一种简单的代换,字符串中可以含任何字符,可以是常数,也可以是表达式,预处理程序对它不作任何检查。如有错误,只能在编译已被宏展开后的源程序时发现。 2. 宏定义不是说明或语句,在行末不必加分号,如加上分号则连分号也一起置换。 3. 宏定义必须写在函数之外,其作用域为宏定义命令起到源程序结 束。如要终止其作用域可使用# undef命令,例如: # define PI 3.14159 main() { …… } # undef PIPI的作用域 f1() ....表示PI只在main函数中有效,在f1中无效。 4. 宏名在源程序中若用引号括起来,则预处理程序不对其作宏代换。 #define OK 100 main() { printf("OK"); printf("\n"); } 上例中定义宏名OK表示100,但在printf语句中OK被引号括起来,因此不作宏代换。程序的运行结果为:OK这表示把“OK”当字符串处理。 5. 宏定义允许嵌套,在宏定义的字符串中可以使用已经定义的宏名。在宏展开时由预处理程序层层代换。例如: #define PI 3.1415926 #define S PI*y*y /* PI是已定义的宏名*/对语句: printf("%f",s);在宏代换后变为: printf("%f",3.1415926*y*y); 6. 习惯上宏名用大写字母表示,以便于与变量区别。但也允许用小写字母。 7. 可用宏定义表示数据类型,使书写方便。例如: #define STU struct stu在程序中可用STU作变量说明: STU body[5],*p;#define INTEGER int 在程序中即可用INTEGER作整型变量说明: INTEGER a,b; 应注意用宏定义表示数据类型和用typedef定义数据说明符的区别。宏定义只是简单的字符串代换,是在预处理完成的,而typedef是在编译时处理的,它不是作简单的代换, 而是对类型说明符重新命名。被命名的标识符具有类型定义说明的功能。请看下面的例子: #define PIN1 int* typedef (int*) PIN2;从形式上看这两者相似, 但在实际使用中却不相同。下面用PIN1,PIN2说明变量时就可以看出它们的区别: PIN1 a,b;在宏代换后变成 int *a,b;表示a是指向整型的指针变量,而b是整型变量。然而:PIN2 a,b;表示a,b都是指向整型的指针变量。因为PIN2是一个类型说明符。由这个例子可见,宏定义虽然也可表示数据类型, 但毕竟是作字符 代换。在使用时要分外小心,以避出错。 8. 对“输出格式”作宏定义,可以减少书写麻烦。例9.3 中就采用了这种方法。 #define P printf #define D "%d\n" #define F "%f\n" main(){ int a=5, c=8, e=11; float b=3.8, d=9.7, f=21.08; P(D F,a,b); P(D F,c,d); P(D F,e,f); } 带参宏定义   C语言允许宏带有参数。在宏定义中的参数称为形式参数, 在宏调用中的参数称为实际参数。对带参数的宏,在调用中,不仅要宏展开, 而且要用实参去代换形参。   带参宏定义的一般形式为: #define 宏名(形参表) 字符串 在字符串中含有各个形参。带参宏调用的一般形式为: 宏名(实参表); 例如: #define M(y) y*y+3*y /*宏定义*/ : k=M(5); /*宏调用*/ : 在宏调用时,用实参5去代替形参y, 经预处理宏展开后的语句 为: k=5*5+3*5 #define MAX(a,b) (a>b)?a:b main(){ int x,y,max; printf("input two numbers: "); scanf("%d%d",&x,&y); max=MAX(x,y); printf("max=%d\n",max); }   上例程序的第一行进行带参宏定义,用宏名MAX表示条件表达式(a>b)?a:b,形参a,b均出现在条件表达式中。程序第七行max=MAX(x, y)为宏调用,实参x,y,将代换形参a,b。宏展开后该语句为: max=(x>y)?x:y;用于计算x,y中的大数。对于带参的宏定义有以下问题需要说明: 1. 带参宏定义中,宏名和形参表之间不能有空格出现。 例如把: #define MAX(a,b) (a>b)?a:b写为: #define MAX (a,b) (a>b)?a:b 将被认为是无参宏定义,宏名MAX代表字符串 (a,b)(a>b)?a:b。 宏展开时,宏调用语句: max=MAX(x,y);将变为: max=(a,b)(a>b)?a:b(x,y);这显然是错误的。 2. 在带参宏定义中,形式参数不分配内存单元,因此不必作类型定义。而宏调用中的实参有具体的值。要用它们去代换形参,因此必须作类型说明。这是与函数中的情况不同的。在函数中,形参和实参是两个不同的量,各有自己的作用域,调用时要把实参值赋予形参,进行“值传递”。而在带参宏中,只是符号代换,不存在值传递的问题。 3. 在宏定义中的形参是标识符,而宏调用中的实参可以是表达式。 #define SQ(y) (y)*(y) main(){ int a,sq; printf("input a number: "); scanf("%d",&a); sq=SQ(a+1); printf("sq=%d\n",sq); }   上例中第一行为宏定义,形参为y。程序第七行宏调用中实参为a+1,是一个表达式,在宏展开时,用a+1代换y,再用(y)*(y) 代换SQ,得到如下语句: sq=(a+1)*(a+1); 这与函数的调用是不同的, 函数调用时要把实参表达式的值求出来再赋予形参。 而宏代换中对实参表达式不作计算直接地照原样代换。 4. 在宏定义中,字符串内的形参通常要用括号括起来以避免出错。 在上例中的宏定义中(y)*(y)表达式的y都用括号括起来,因此结果是正确的。如果去掉括号,把程序改为以下形式: #define SQ(y) y*y main(){ int a,sq; printf("input a number: "); scanf("%d",&a); sq=SQ(a+1); printf("sq=%d\n",sq); } 运行结果为:input a number:3 sq=7 同样输入3,但结果却是不一样的。问题在哪里呢? 这是由于代换只作符号代换而不作其它处理而造成的。 宏代换后将得到以下语句: sq=a+1*a+1; 由于a为3故sq的值为7。这显然与题意相违,因此参数两边的括号是不能少的。即使在参数两边加括号还是不够的,请看下面程序: #define SQ(y) (y)*(y) main(){ int a,sq; printf("input a number: "); scanf("%d",&a); sq=160/SQ(a+1); printf("sq=%d\n",sq); }   本程序与前例相比,只把宏调用语句改为: sq=160/SQ(a+1); 运行本程序如输入值仍为3时,希望结果为10。但实际运行的结果如下:input a number:3 sq=160为什么会得这样的结果呢?分析宏调用语句,在宏代换之后变为: sq=160/(a+1)*(a+1);a为3时,由于“/”和“*”运算符优先级和结合性相同, 则先作160/(3+1)得40,再作40*(3+1)最后得160。为了得到正确答案应在宏定义中的整个字符串外加括号, 程序修改如下 #define SQ(y) ((y)*(y)) main(){ int a,sq; printf("input a number: "); scanf("%d",&a); sq=160/SQ(a+1); printf("sq=%d\n",sq); } 以上讨论说明,对于宏定义不仅应在参数两侧加括号, 也应在整个字符串外加括号。 5. 带参的宏和带参函数很相似,但有本质上的不同,除上面已谈到的各点外,把同一表达式用函数处理与用宏处理两者的结果有可能是不同的。main(){ int i=1; while(i<=5) printf("%d\n",SQ(i++)); } SQ(int y) { return((y)*(y)); }#define SQ(y) ((y)*(y)) main(){ int i=1; while(i<=5) printf("%d\n",SQ(i++)); }   在上例中函数名为SQ,形参为Y,函数体表达式为((y)*(y))。在例9.6中宏名为SQ,形参也为y,字符串表达式为(y)*(y))。 两例是相同的。例9.6的函数调用为SQ(i++),例9.7的宏调用为SQ(i++),实参也是相同的。从输出结果来看,却大不相同。分析如下:在例9.6中,函数调用是把实参i值传给形参y后自增1。 然后输出函数值。因而要循环5次。输出1~5的平方值。而在例9.7中宏调用时,只作代换。SQ(i++)被代换为((i++)*(i++))。在第一次循环时,由于i等于1,其计算过程为:表达式中前一个i初值为1,然后i自增1变为2,因此表达式中第2个i初值为2,两相乘的结果也为2,然后i值再自增1,得3。在第二次循环时,i值已有初值为3,因此表达式中前一个i为3,后一个i为4, 乘积为12,然后i再自增1变为5。进入第三次循环,由于i 值已为5,所以这将是最后一次循环。计算表达式的值为5*6等于30。i值再自增1变为6,不再满足循环条件,停止循环。从以上分析可以看出函数调用和宏调用二者在形式上相似, 在本质上是完全不同的。 6. 宏定义也可用来定义多个语句,在宏调用时,把这些语句又代换到源程序内。看下面的例子。 #define SSSV(s1,s2,s3,v) s1=l*w;s2=l*h;s3=w*h;v=w*l*h; main(){ int l=3,w=4,h=5,sa,sb,sc,vv; SSSV(sa,sb,sc,vv); printf("sa=%d\nsb=%d\nsc=%d\nvv=%d\n",sa,sb,sc,vv); }   程序第一行为宏定义,用宏名SSSV表示4个赋值语句,4 个形参分别为4个赋值符左部的变量。在宏调用时,把4 个语句展开并用实参代替形参。使计算结果送入实参之中。 文件包含   文件包含是C预处理程序的另一个重要功能。文件包含命令行的一般形式为: #include"文件名" 在前面我们已多次用此命令包含过库函数的头文件。例如: #include"stdio.h" #include"math.h" 文件包含命令的功能是把指定的文件插入该命令行位置取代该命令行, 从而把指定的文件和当前的源程序文件连成一个源文件。在程序设计中,文件包含是很有用的。 一个大的程序可以分为多个模块,由多个程序员分别编程。 有些公用的符号常量或宏定义等可单独组成一个文件, 在其它文件的开头用包含命令包含该文件即可使用。这样,可避免在每个文件开头都去书写那些公用量, 从而节省时间,并减少出错。 对文件包含命令还要说明以下几点: 1. 包含命令中的文件名可以用双引号括起来,也可以用尖括号括起来。例如以下写法都是允许的: #include"stdio.h" #include 但是这两种形式是有区别的:使用尖括号表示在包含文件目录中去查找(包含目录是由用户在设置环境时设置的), 而不在源文件目录去查找; 使用双引号则表示首先在当前的源文件目录中查找,若未找到才到包含目录中去查找。 用户编程时可根据自己文件所在的目录来选择某一种命令形式。 2. 一个include命令只能指定一个被包含文件, 若有多个文件要包含,则需用多个include命令。3. 文件包含允许嵌套,即在一个被包含的文件中又可以包含另一个文件。 条件编译 预处理程序提供了条件编译的功能。 可以按不同的条件去编译不同的程序部分,因而产生不同的目标代码文件。 这对于程序的移植和调试是很有用的。 条件编译有三种形式,下面分别介绍: 1. 第一种形式: #ifdef 标识符 程序段1 #else 程序段2 #endif 它的功能是,如果标识符已被 #define命令定义过则对程序段1进行编译;否则对程序段2进行编译。如果没有程序段2(它为空),本格式中的#else可以没有, 即可以写为: #ifdef 标识符 程序段 #endif #define NUM ok main(){ struct stu { int num; char *name; char sex; float score; } *ps; ps=(struct stu*)malloc(sizeof(struct stu)); ps->num=102; ps->name="Zhang ping"; ps->sex='M'; ps->score=62.5; #ifdef NUM printf("Number=%d\nScore=%f\n",ps->num,ps->score); #else printf("Name=%s\nSex=%c\n",ps->name,ps->sex); #endif free(ps); }   由于在程序的第16行插入了条件编译预处理命令, 因此要根据NUM是否被定义过来决定编译那一个printf语句。而在程序的第一行已对NUM作过宏定义,因此应对第一个printf语句作编译故运行结果是输出了学号和成绩。在程序的第一行宏定义中,定义NUM表示字符串OK,其实也可以为任何字符串,甚至不给出任何字符串,写为: #define NUM 也具有同样的意义。 只有取消程序的第一行才会去编译第二个printf语句。读者可上机试作。 2. 第二种形式: #ifndef 标识符 程序段1 #else 程序段2 #endif 与第一种形式的区别是将“ifdef”改为“ifndef”。它的功能是,如果标识符未被#define命令定义过则对程序段1进行编译, 否则对程序段2进行编译。这与第一种形式的功能正相反。 3. 第三种形式: #if 常量表达式 程序段1 #else 程序段2 #endif 它的功能是,如常量表达式的值为真(非0),则对程序段1 进行编译,否则对程序段2进行编译。因此可以使程序在不同条件下,完成不同的功能 #define R 1 main(){ float c,r,s; printf ("input a number: "); scanf("%f",&c); #if R r=3.14159*c*c; printf("area of round is: %f\n",r); #else s=c*c; printf("area of square is: %f\n",s); #endif }   本例中采用了第三种形式的条件编译。在程序第一行宏定义中,定义R为1,因此在条件编译时,常量表达式的值为真, 故计算并输出圆面积。上面介绍的条件编译当然也可以用条件语句来实现。 但是用条件语句将会对整个源程序进行编译,生成的目标代码程序很长,而采用条件编译,则根据条件只编译其中的程序段1或程序段2, 生成的目标程序较短。如果条件选择的程序段很长, 采用条件编译的方法是十分必要的。 本章小结 1. 预处理功能是C语言特有的功能,它是在对源程序正式编译前由预处理程序完成的。程序员在程序中用预处理命令来调用这些功能。 2. 宏定义是用一个标识符来表示一个字符串,这个字符串可以是常量、变量或表达式。在宏调用中将用该字符串代换宏名。 3. 宏定义可以带有参数,宏调用时是以实参代换形参。而不是“值传送”。 4. 为了避免宏代换时发生错误,宏定义中的字符串应加括号,字符串中出现的形式参数两边也应加括号。 5. 文件包含是预处理的一个重要功能,它可用来把多个源文件连接成一个源文件进行编译,结果将生成一个目标文件。 6. 条件编译允许只编译源程序中满足条件的程序段,使生成的目标程序较短,从而减少了内存的开销并提高了程序的效率。 7. 使用预处理功能便于程序的修改、阅读、移植和调试,也便于实现模块化程序设计。 第十章:文件 文件 文件的基本概念   所谓“文件”是指一组相关数据的有序集合。 这个数据集有一个名称,叫做文件名。 实际上在前面的各章中我们已经多次使用了文件,例如源程序文件、目标文件、可执行文件、库文件 (头文件)等。文件通常是驻留在外部介质(如磁盘等)上的, 在使用时才调入内存中来。从不同的角度可对文件作不同的分类。从用户的角度看,文件可分为普通文件和设备文件两种。   普通文件是指驻留在磁盘或其它外部介质上的一个有序数据集,可以是源文件、目标文件、可执行程序; 也可以是一组待输入处理的原始数据,或者是一组输出的结果。对于源文件、目标文件、 可执行程序可以称作程序文件,对输入输出数据可称作数据文件。   设备文件是指与主机相联的各种外部设备,如显示器、打印机、键盘等。在操作系统中,把外部设备也看作是一个文件来进行管理,把它们的输入、输出等同于对磁盘文件的读和写。 通常把显示器定义为标准输出文件, 一般情况下在屏幕上显示有关信息就是向标准输出文件输出。如前面经常使用的printf,putchar 函数就是这类输出。键盘通常被指定标准的输入文件, 从键盘上输入就意味着从标准输入文件上输入数据。scanf,getchar函数就属于这类输入。   从文件编码的方式来看,文件可分为ASCII码文件和二进制码文件两种。   ASCII文件也称为文本文件,这种文件在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。例如,数5678的存储形式为: ASC码:  00110101 00110110 00110111 00111000      ↓     ↓    ↓    ↓ 十进制码: 5     6    7    8 共占用4个字节。ASCII码文件可在屏幕上按字符显示, 例如源程序文件就是ASCII文件,用DOS命令TYPE可显示文件的内容。 由于是按字符显示,因此能读懂文件内容。   二进制文件是按二进制的编码方式来存放文件的。 例如, 数5678的存储形式为: 00010110 00101110只占二个字节。二进制文件虽然也可在屏幕上显示, 但其内容无法读懂。C系统在处理这些文件时,并不区分类型,都看成是字符流,按字节进行处理。 输入输出字符流的开始和结束只由程序控制而不受物理符号(如回车符)的控制。 因此也把这种文件称作“流式文件”。   本章讨论流式文件的打开、关闭、读、写、 定位等各种操作。文件指针在C语言中用一个指针变量指向一个文件, 这个指针称为文件指针。通过文件指针就可对它所指的文件进行各种操作。 定义说明文件指针的一般形式为: FILE* 指针变量标识符; 其中FILE应为大写,它实际上是由系统定义的一个结构, 该结构中含有文件名、文件状态和文件当前位置等信息。 在编写源程序时不必关心FILE结构的细节。例如:FILE *fp; 表示fp是指向FILE结构的指针变量,通过fp 即可找存放某个文件信息的结构变量,然后按结构变量提供的信息找到该文件, 实施对文件的操作。习惯上也笼统地把fp称为指向一个文件的指针。文件的打开与关闭文件在进行读写操作之前要先打开,使用完毕要关闭。 所谓打开文件,实际上是建立文件的各种有关信息, 并使文件指针指向该文件,以便进行其它操作。关闭文件则断开指针与文件之间的联系,也就禁止再对该文件进行操作。   在C语言中,文件操作都是由库函数来完成的。 在本章内将介绍主要的文件操作函数。 文件打开函数fopen   fopen函数用来打开一个文件,其调用的一般形式为: 文件指针名=fopen(文件名,使用文件方式) 其中,“文件指针名”必须是被说明为FILE 类型的指针变量,“文件名”是被打开文件的文件名。 “使用文件方式”是指文件的类型和操作要求。“文件名”是字符串常量或字符串数组。例如: FILE *fp; fp=("file a","r"); 其意义是在当前目录下打开文件file a, 只允许进行“读”操作,并使fp指向该文件。 又如: FILE *fphzk fphzk=("c:\\hzk16',"rb") 其意义是打开C驱动器磁盘的根目录下的文件hzk16, 这是一个二进制文件,只允许按二进制方式进行读操作。两个反斜线“\\ ”中的第一个表示转义字符,第二个表示根目录。使用文件的方式共有12种,下面给出了它们的符号和意义。 文件使用方式        意 义 “rt”      只读打开一个文本文件,只允许读数据 “wt”      只写打开或建立一个文本文件,只允许写数据 “at”      追加打开一个文本文件,并在文件末尾写数据 “rb”      只读打开一个二进制文件,只允许读数据 “wb”       只写打开或建立一个二进制文件,只允许写数据 “ab”       追加打开一个二进制文件,并在文件末尾写数据 “rt+”      读写打开一个文本文件,允许读和写 “wt+”      读写打开或建立一个文本文件,允许读写 “at+”      读写打开一个文本文件,允许读,或在文件末追加数 据 “rb+”      读写打开一个二进制文件,允许读和写 “wb+”      读写打开或建立一个二进制文件,允许读和写 “ab+”      读写打开一个二进制文件,允许读,或在文件末追加数据 对于文件使用方式有以下几点说明: 1. 文件使用方式由r,w,a,t,b,+六个字符拼成,各字符的含义是: r(read): 读 w(write): 写 a(append): 追加 t(text): 文本文件,可省略不写 b(banary): 二进制文件 +: 读和写 2. 凡用“r”打开一个文件时,该文件必须已经存在, 且只能从该文件读出。 3. 用“w”打开的文件只能向该文件写入。 若打开的文件不存在,则以指定的文件名建立该文件,若打开的文件已经存在,则将该文件删去,重建一个新文件。 4. 若要向一个已存在的文件追加新的信息,只能用“a ”方式打开文件。但此时该文件必须是存在的,否则将会出错。 5. 在打开一个文件时,如果出错,fopen将返回一个空指针值NULL。在程序中可以用这一信息来判别是否完成打开文件的工作,并作相应的处理。因此常用以下程序段打开文件: if((fp=fopen("c:\\hzk16","rb")==NULL) { printf("\nerror on open c:\\hzk16 file!"); getch(); exit(1); }   这段程序的意义是,如果返回的指针为空,表示不能打开C盘根目录下的hzk16文件,则给出提示信息“error on open c:\ hzk16file!”,下一行getch()的功能是从键盘输入一个字符,但不在屏幕上显示。在这里,该行的作用是等待, 只有当用户从键盘敲任一键时,程序才继续执行, 因此用户可利用这个等待时间阅读出错提示。敲键后执行exit(1)退出程序。 6. 把一个文本文件读入内存时,要将ASCII码转换成二进制码, 而把文件以文本方式写入磁盘时,也要把二进制码转换成ASCII码,因此文本文件的读写要花费较多的转换时间。对二进制文件的读写不存在这种转换。 7. 标准输入文件(键盘),标准输出文件(显示器 ),标准出错输出(出错信息)是由系统打开的,可直接使用。文件关闭函数fclose文件一旦使用完毕,应用关闭文件函数把文件关闭, 以避免文件的数据丢失等错误。 fclose函数 调用的一般形式是: fclose(文件指针); 例如: fclose(fp); 正常完成关闭文件操作时,fclose函数返回值为0。如返回非零值则表示有错误发生。文件的读写对文件的读和写是最常用的文件操作。 在C语言中提供了多种文件读写的函数: ·字符读写函数 :fgetc和fputc ·字符串读写函数:fgets和fputs ·数据块读写函数:freed和fwrite ·格式化读写函数:fscanf和fprinf   下面分别予以介绍。使用以上函数都要求包含头文件stdio.h。字符读写函数fgetc和fputc字符读写函数是以字符(字节)为单位的读写函数。 每次可从文件读出或向文件写入一个字符。 一、读字符函数fgetc   fgetc函数的功能是从指定的文件中读一个字符,函数调用的形式为: 字符变量=fgetc(文件指针); 例如:ch=fgetc(fp);其意义是从打开的文件fp中读取一个字符并送入ch中。   对于fgetc函数的使用有以下几点说明: 1. 在fgetc函数调用中,读取的文件必须是以读或读写方式打开的。 2. 读取字符的结果也可以不向字符变量赋值,例如:fgetc(fp);但是读出的字符不能保存。 3. 在文件内部有一个位置指针。用来指向文件的当前读写字节。在文件打开时,该指针总是指向文件的第一个字节。使用fgetc 函数后, 该位置指针将向后移动一个字节。 因此可连续多次使用fgetc函数,读取多个字符。 应注意文件指针和文件内部的位置指针不是一回事。文件指针是指向整个文件的,须在程序中定义说明,只要不重新赋值,文件指针的值是不变的。文件内部的位置指针用以指示文件内部的当前读写位置,每读写一次,该指针均向后移动,它不需在程序中定义说明,而是由系统自动设置的。 [例10.1]读入文件e10-1.c,在屏幕上输出。 #include main() { FILE *fp; char ch; if((fp=fopen("e10_1.c","rt"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } ch=fgetc(fp); while (ch!=EOF) { putchar(ch); ch=fgetc(fp); } fclose(fp); }   本例程序的功能是从文件中逐个读取字符,在屏幕上显示。 程序定义了文件指针fp,以读文本文件方式打开文件“e10_1.c”, 并使fp指向该文件。如打开文件出错, 给出提示并退出程序。程序第12行先读出一个字符,然后进入循环, 只要读出的字符不是文件结束标志(每个文件末有一结束标志EOF)就把该字符显示在屏幕上,再读入下一字符。每读一次,文件内部的位置指针向后移动一个字符,文件结束时,该指针指向EOF。执行本程序将显示整个文件。 二、写字符函数fputc   fputc函数的功能是把一个字符写入指定的文件中,函数调用的 形式为: fputc(字符量,文件指针); 其中,待写入的字符量可以是字符常量或变量,例如:fputc('a',fp);其意义是把字符a写入fp所指向的文件中。   对于fputc函数的使用也要说明几点: 1. 被写入的文件可以用、写、读写,追加方式打开,用写或读写方式打开一个已存在的文件时将清除原有的文件内容,写入字符从文件首开始。如需保留原有文件内容,希望写入的字符以文件末开始存放,必须以追加方式打开文件。被写入的文件若不存在,则创建该文件。 2. 每写入一个字符,文件内部位置指针向后移动一个字节。 3. fputc函数有一个返回值,如写入成功则返回写入的字符, 否则返回一个EOF。可用此来判断写入是否成功。 [例10.2]从键盘输入一行字符,写入一个文件, 再把该文件内容读出显示在屏幕上。 #include main() { FILE *fp; char ch; if((fp=fopen("string","wt+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("input a string:\n"); ch=getchar(); while (ch!='\n') { fputc(ch,fp); ch=getchar(); } rewind(fp); ch=fgetc(fp); while(ch!=EOF) { putchar(ch); ch=fgetc(fp); } printf("\n"); fclose(fp); }   程序中第6行以读写文本文件方式打开文件string。程序第13行从键盘读入一个字符后进入循环,当读入字符不为回车符时, 则把该字符写入文件之中,然后继续从键盘读入下一字符。 每输入一个字符,文件内部位置指针向后移动一个字节。写入完毕, 该指针已指向文件末。如要把文件从头读出,须把指针移向文件头, 程序第19行rewind函数用于把fp所指文件的内部位置指针移到文件头。 第20至25行用于读出文件中的一行内容。 [例10.3]把命令行参数中的前一个文件名标识的文件, 复制到后一个文件名标识的文件中, 如命令行中只有一个文件名则把该文件写到标准输出文件(显示器)中。 #include main(int argc,char *argv[]) { FILE *fp1,*fp2; char ch; if(argc==1) { printf("have not enter file name strike any key exit"); getch(); exit(0); } if((fp1=fopen(argv[1],"rt"))==NULL) { printf("Cannot open %s\n",argv[1]); getch(); exit(1); } if(argc==2) fp2=stdout; else if((fp2=fopen(argv[2],"wt+"))==NULL) { printf("Cannot open %s\n",argv[1]); getch(); exit(1); } while((ch=fgetc(fp1))!=EOF) fputc(ch,fp2); fclose(fp1); fclose(fp2); }   本程序为带参的main函数。程序中定义了两个文件指针 fp1 和fp2,分别指向命令行参数中给出的文件。如命令行参数中没有给出文件名,则给出提示信息。程序第18行表示如果只给出一个文件名,则使fp2指向标准输出文件(即显示器)。程序第25行至28行用循环语句逐个读出文件1中的字符再送到文件2中。再次运行时,给出了一个文件名(由例10.2所建立的文件), 故输出给标准输出文件stdout,即在显示器上显示文件内容。第三次运行,给出了二个文件名,因此把string中的内容读出,写入到OK之中。可用DOS命令type显示OK的内容:字符串读写函数fgets和fputs 一、读字符串函数fgets函数的功能是从指定的文件中读一个字符串到字符数组中,函数调用的形式为: fgets(字符数组名,n,文件指针); 其中的n是一个正整数。表示从文件中读出的字符串不超过 n-1个字符。在读入的最后一个字符后加上串结束标志'\0'。例如:fgets(str,n,fp);的意义是从fp所指的文件中读出n-1个字符送入字符数组str中。 [例10.4]从e10_1.c文件中读入一个含10个字符的字符串。 #include main() { FILE *fp; char str[11]; if((fp=fopen("e10_1.c","rt"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } fgets(str,11,fp); printf("%s",str); fclose(fp); }   本例定义了一个字符数组str共11个字节,在以读文本文件方式打开文件e101.c后,从中读出10个字符送入str数组,在数组最后一个单元内将加上'\0',然后在屏幕上显示输出str数组。输出的十个字符正是例10.1程序的前十个字符。   对fgets函数有两点说明: 1. 在读出n-1个字符之前,如遇到了换行符或EOF,则读出结束。 2. fgets函数也有返回值,其返回值是字符数组的首地址。 二、写字符串函数fputs fputs函数的功能是向指定的文件写入一个字符串,其调用形式为: fputs(字符串,文件指针) 其中字符串可以是字符串常量,也可以是字符数组名, 或指针 变量,例如: fputs(“abcd“,fp); 其意义是把字符串“abcd”写入fp所指的文件之中。[例10.5]在例10.2中建立的文件string中追加一个字符串。 #include main() { FILE *fp; char ch,st[20]; if((fp=fopen("string","at+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("input a string:\n"); scanf("%s",st); fputs(st,fp); rewind(fp); ch=fgetc(fp); while(ch!=EOF) { putchar(ch); ch=fgetc(fp); } printf("\n"); fclose(fp); }   本例要求在string文件末加写字符串,因此,在程序第6行以追加读写文本文件的方式打开文件string 。 然后输入字符串, 并用fputs函数把该串写入文件string。在程序15行用rewind函数把文件内部位置指针移到文件首。 再进入循环逐个显示当前文件中的全部内容。 数据块读写函数fread和fwrite   C语言还提供了用于整块数据的读写函数。 可用来读写一组数据,如一个数组元素,一个结构变量的值等。读数据块函数调用的一般形式为: fread(buffer,size,count,fp); 写数据块函数调用的一般形式为: fwrite(buffer,size,count,fp); 其中buffer是一个指针,在fread函数中,它表示存放输入数据的首地址。在fwrite函数中,它表示存放输出数据的首地址。 size 表示数据块的字节数。count 表示要读写的数据块块数。fp 表示文件指针。 例如: fread(fa,4,5,fp); 其意义是从fp所指的文件中,每次读4个字节(一个实数)送入实数组fa中,连续读5次,即读5个实数到fa中。 [例10.6]从键盘输入两个学生数据,写入一个文件中, 再读出这两个学生的数据显示在屏幕上。 #include struct stu { char name[10]; int num; int age; char addr[15]; }boya[2],boyb[2],*pp,*qq; main() { FILE *fp; char ch; int i; pp=boya; qq=boyb; if((fp=fopen("stu_list","wb+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("\ninput data\n"); for(i=0;i<2;i++,pp++) scanf("%s%d%d%s",pp->name,&pp->num,&pp->age,pp->addr); pp=boya; fwrite(pp,sizeof(struct stu),2,fp); rewind(fp); fread(qq,sizeof(struct stu),2,fp); printf("\n\nname\tnumber age addr\n"); for(i=0;i<2;i++,qq++) printf("%s\t%5d%7d%s\n",qq->name,qq->num,qq->age,qq->addr); fclose(fp); }   本例程序定义了一个结构stu,说明了两个结构数组boya和 boyb以及两个结构指针变量pp和qq。pp指向boya,qq指向boyb。程序第16行以读写方式打开二进制文件“stu_list”,输入二个学生数据之后,写入该文件中, 然后把文件内部位置指针移到文件首,读出两块学生数据后,在屏幕上显示。 格式化读写函数fscanf和fprintf fscanf函数,fprintf函数与前面使用的scanf和printf 函数的功能相似,都是格式化读写函数。 两者的区别在于 fscanf 函数和fprintf函数的读写对象不是键盘和显示器,而是磁盘文件。这两个函数的调用格式为: fscanf(文件指针,格式字符串,输入表列); fprintf(文件指针,格式字符串,输出表列); 例如: fscanf(fp,"%d%s",&i,s); fprintf(fp,"%d%c",j,ch); 用fscanf和fprintf函数也可以完成例10.6的问题。修改后的程序如例10.7所示。 [例10.7] #include struct stu { char name[10]; int num; int age; char addr[15]; }boya[2],boyb[2],*pp,*qq; main() { FILE *fp; char ch; int i; pp=boya; qq=boyb; if((fp=fopen("stu_list","wb+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("\ninput data\n"); for(i=0;i<2;i++,pp++) scanf("%s%d%d%s",pp->name,&pp->num,&pp->age,pp->addr); pp=boya; for(i=0;i<2;i++,pp++) fprintf(fp,"%s %d %d %s\n",pp->name,pp->num,pp->age,pp-> addr); rewind(fp); for(i=0;i<2;i++,qq++) fscanf(fp,"%s %d %d %s\n",qq->name,&qq->num,&qq->age,qq->addr); printf("\n\nname\tnumber age addr\n"); qq=boyb; for(i=0;i<2;i++,qq++) printf("%s\t%5d %7d %s\n",qq->name,qq->num, qq->age, qq->addr); fclose(fp); }   与例10.6相比,本程序中fscanf和fprintf函数每次只能读写一个结构数组元素,因此采用了循环语句来读写全部数组元素。 还要注意指针变量pp,qq由于循环改变了它们的值,因此在程序的25和32行分别对它们重新赋予了数组的首地址。 文件的随机读写   前面介绍的对文件的读写方式都是顺序读写, 即读写文件只能从头开始,顺序读写各个数据。 但在实际问题中常要求只读写文件中某一指定的部分。 为了解决这个问题可移动文件内部的位置指针到需要读写的位置,再进行读写,这种读写称为随机读写。 实现随机读写的关键是要按要求移动位置指针,这称为文件的定位。文件定位移动文件内部位置指针的函数主要有两个, 即 rewind 函数和fseek函数。   rewind函数前面已多次使用过,其调用形式为: rewind(文件指针); 它的功能是把文件内部的位置指针移到文件首。 下面主要介绍 fseek函数。   fseek函数用来移动文件内部位置指针,其调用形式为: fseek(文件指针,位移量,起始点); 其中:“文件指针”指向被移动的文件。 “位移量”表示移动的字节数,要求位移量是long型数据,以便在文件长度大于64KB 时不会出错。当用常量表示位移量时,要求加后缀“L”。“起始点”表示从何处开始计算位移量,规定的起始点有三种:文件首,当前位置和文件尾。 其表示方法如表10.2。 起始点    表示符号    数字表示 ────────────────────────── 文件首    SEEK—SET    0 当前位置   SEEK—CUR    1 文件末尾   SEEK—END     2 例如: fseek(fp,100L,0);其意义是把位置指针移到离文件首100个字节处。还要说明的是fseek函数一般用于二进制文件。在文本文件中由于要进行转换,故往往计算的位置会出现错误。文件的随机读写在移动位置指针之后, 即可用前面介绍的任一种读写函数进行读写。由于一般是读写一个数据据块,因此常用fread和fwrite函数。下面用例题来说明文件的随机读写。 [例10.8]在学生文件stu list中读出第二个学生的数据。 #include struct stu { char name[10]; int num; int age; char addr[15]; }boy,*qq; main() { FILE *fp; char ch; int i=1; qq=&boy; if((fp=fopen("stu_list","rb"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } rewind(fp); fseek(fp,i*sizeof(struct stu),0); fread(qq,sizeof(struct stu),1,fp); printf("\n\nname\tnumber age addr\n"); printf("%s\t%5d %7d %s\n",qq->name,qq->num,qq->age, qq->addr); }   文件stu_list已由例10.6的程序建立,本程序用随机读出的方法读出第二个学生的数据。程序中定义boy为stu类型变量,qq为指向boy的指针。以读二进制文件方式打开文件,程序第22行移动文件位置指针。其中的i值为1,表示从文件头开始,移动一个stu类型的长度, 然后再读出的数据即为第二个学生的数据。 文件检测函数 C语言中常用的文件检测函数有以下几个。 一、文件结束检测函数feof函数调用格式: feof(文件指针); 功能:判断文件是否处于文件结束位置,如文件结束,则返回值为1,否则为0。 二、读写文件出错检测函数ferror函数调用格式: ferror(文件指针); 功能:检查文件在用各种输入输出函数进行读写时是否出错。 如ferror返回值为0表示未出错,否则表示有错。 三、文件出错标志和文件结束标志置0函数clearerr函数调用格式: clearerr(文件指针); 功能:本函数用于清除出错标志和文件结束标志,使它们为0值。 C库文件 C系统提供了丰富的系统文件,称为库文件,C的库文件分为两类,一类是扩展名为".h"的文件,称为头文件, 在前面的包含命令中我们已多次使用过。在".h"文件中包含了常量定义、 类型定义、宏定义、函数原型以及各种编译选择设置等信息。另一类是函数库,包括了各种函数的目标代码,供用户在程序中调用。 通常在程序中调用一个库函数时,要在调用之前包含该函数原型所在的".h" 文件。 在附录中给出了全部库函数。 ALLOC.H    说明内存管理函数(分配、释放等)。 ASSERT.H    定义 assert调试宏。 BIOS.H     说明调用IBM—PC ROM BIOS子程序的各个函数。 CONIO.H    说明调用DOS控制台I/O子程序的各个函数。 CTYPE.H    包含有关字符分类及转换的名类信息(如 isalpha和toascii等)。 DIR.H     包含有关目录和路径的结构、宏定义和函数。 DOS.H     定义和说明MSDOS和8086调用的一些常量和函数。 ERRON.H    定义错误代码的助记符。 FCNTL.H    定义在与open库子程序连接时的符号常量。 FLOAT.H    包含有关浮点运算的一些参数和函数。 GRAPHICS.H   说明有关图形功能的各个函数,图形错误代码的常量定义,正对不同驱动程序的各种颜色值,及函数用到的一些特殊结构。 IO.H      包含低级I/O子程序的结构和说明。 LIMIT.H    包含各环境参数、编译时间限制、数的范围等信息。 MATH.H     说明数学运算函数,还定了 HUGE VAL 宏, 说明了matherr和matherr子程序用到的特殊结构。 MEM.H     说明一些内存操作函数(其中大多数也在STRING.H 中说明)。 PROCESS.H   说明进程管理的各个函数,spawn…和EXEC …函数的结构说明。 SETJMP.H    定义longjmp和setjmp函数用到的jmp buf类型, 说明这两个函数。 SHARE.H    定义文件共享函数的参数。 SIGNAL.H    定义SIG[ZZ(Z] [ZZ)]IGN和SIG[ZZ(Z] [ZZ)]DFL常量,说明rajse和signal两个函数。 STDARG.H    定义读函数参数表的宏。(如vprintf,vscarf函数)。 STDDEF.H    定义一些公共数据类型和宏。 STDIO.H    定义Kernighan和Ritchie在Unix System V 中定义的标准和扩展的类型和宏。还定义标准I/O 预定义流:stdin,stdout和stderr,说明 I/O流子程序。 STDLIB.H    说明一些常用的子程序:转换子程序、搜索/ 排序子程序等。 STRING.H    说明一些串操作和内存操作函数。 SYS\STAT.H   定义在打开和创建文件时用到的一些符号常量。 SYS\TYPES.H  说明ftime函数和timeb结构。 SYS\TIME.H   定义时间的类型time[ZZ(Z] [ZZ)]t。 TIME.H     定义时间转换子程序asctime、localtime和gmtime的结构,ctime、 difftime、 gmtime、 localtime和stime用到的类型,并提供这些函数的原型。 VALUE.H    定义一些重要常量, 包括依赖于机器硬件的和为与Unix System V相兼容而说明的一些常量,包括浮点和双精度值的范围。 本章小结 1. C系统把文件当作一个“流”,按字节进行处理。 2. C文件按编码方式分为二进制文件和ASCII文件。 3. C语言中,用文件指针标识文件,当一个文件被 打开时, 可取得该文件指针。 4. 文件在读写之前必须打开,读写结束必须关闭。 5. 文件可按只读、只写、读写、追加四种操作方式打开,同时还必须指定文件的类型是二进制文件还是文本文件。 6. 文件可按字节,字符串,数据块为单位读写,文件也可按指定的格式进行读写。 7. 文件内部的位置指针可指示当前的读写位置,移动该指针可以对文件实现随机读写。 资料收集:beck Copyright 2002 www.vcok.com, All Rights Reserved 第十章:文件 文件 文件的基本概念   所谓“文件”是指一组相关数据的有序集合。 这个数据集有一个名称,叫做文件名。 实际上在前面的各章中我们已经多次使用了文件,例如源程序文件、目标文件、可执行文件、库文件 (头文件)等。文件通常是驻留在外部介质(如磁盘等)上的, 在使用时才调入内存中来。从不同的角度可对文件作不同的分类。从用户的角度看,文件可分为普通文件和设备文件两种。   普通文件是指驻留在磁盘或其它外部介质上的一个有序数据集,可以是源文件、目标文件、可执行程序; 也可以是一组待输入处理的原始数据,或者是一组输出的结果。对于源文件、目标文件、 可执行程序可以称作程序文件,对输入输出数据可称作数据文件。   设备文件是指与主机相联的各种外部设备,如显示器、打印机、键盘等。在操作系统中,把外部设备也看作是一个文件来进行管理,把它们的输入、输出等同于对磁盘文件的读和写。 通常把显示器定义为标准输出文件, 一般情况下在屏幕上显示有关信息就是向标准输出文件输出。如前面经常使用的printf,putchar 函数就是这类输出。键盘通常被指定标准的输入文件, 从键盘上输入就意味着从标准输入文件上输入数据。scanf,getchar函数就属于这类输入。   从文件编码的方式来看,文件可分为ASCII码文件和二进制码文件两种。   ASCII文件也称为文本文件,这种文件在磁盘中存放时每个字符对应一个字节,用于存放对应的ASCII码。例如,数5678的存储形式为: ASC码:  00110101 00110110 00110111 00111000      ↓     ↓    ↓    ↓ 十进制码: 5     6    7    8 共占用4个字节。ASCII码文件可在屏幕上按字符显示, 例如源程序文件就是ASCII文件,用DOS命令TYPE可显示文件的内容。 由于是按字符显示,因此能读懂文件内容。   二进制文件是按二进制的编码方式来存放文件的。 例如, 数5678的存储形式为: 00010110 00101110只占二个字节。二进制文件虽然也可在屏幕上显示, 但其内容无法读懂。C系统在处理这些文件时,并不区分类型,都看成是字符流,按字节进行处理。 输入输出字符流的开始和结束只由程序控制而不受物理符号(如回车符)的控制。 因此也把这种文件称作“流式文件”。   本章讨论流式文件的打开、关闭、读、写、 定位等各种操作。文件指针在C语言中用一个指针变量指向一个文件, 这个指针称为文件指针。通过文件指针就可对它所指的文件进行各种操作。 定义说明文件指针的一般形式为: FILE* 指针变量标识符; 其中FILE应为大写,它实际上是由系统定义的一个结构, 该结构中含有文件名、文件状态和文件当前位置等信息。 在编写源程序时不必关心FILE结构的细节。例如:FILE *fp; 表示fp是指向FILE结构的指针变量,通过fp 即可找存放某个文件信息的结构变量,然后按结构变量提供的信息找到该文件, 实施对文件的操作。习惯上也笼统地把fp称为指向一个文件的指针。文件的打开与关闭文件在进行读写操作之前要先打开,使用完毕要关闭。 所谓打开文件,实际上是建立文件的各种有关信息, 并使文件指针指向该文件,以便进行其它操作。关闭文件则断开指针与文件之间的联系,也就禁止再对该文件进行操作。   在C语言中,文件操作都是由库函数来完成的。 在本章内将介绍主要的文件操作函数。 文件打开函数fopen   fopen函数用来打开一个文件,其调用的一般形式为: 文件指针名=fopen(文件名,使用文件方式) 其中,“文件指针名”必须是被说明为FILE 类型的指针变量,“文件名”是被打开文件的文件名。 “使用文件方式”是指文件的类型和操作要求。“文件名”是字符串常量或字符串数组。例如: FILE *fp; fp=("file a","r"); 其意义是在当前目录下打开文件file a, 只允许进行“读”操作,并使fp指向该文件。 又如: FILE *fphzk fphzk=("c:\\hzk16',"rb") 其意义是打开C驱动器磁盘的根目录下的文件hzk16, 这是一个二进制文件,只允许按二进制方式进行读操作。两个反斜线“\\ ”中的第一个表示转义字符,第二个表示根目录。使用文件的方式共有12种,下面给出了它们的符号和意义。 文件使用方式        意 义 “rt”      只读打开一个文本文件,只允许读数据 “wt”      只写打开或建立一个文本文件,只允许写数据 “at”      追加打开一个文本文件,并在文件末尾写数据 “rb”      只读打开一个二进制文件,只允许读数据 “wb”       只写打开或建立一个二进制文件,只允许写数据 “ab”       追加打开一个二进制文件,并在文件末尾写数据 “rt+”      读写打开一个文本文件,允许读和写 “wt+”      读写打开或建立一个文本文件,允许读写 “at+”      读写打开一个文本文件,允许读,或在文件末追加数 据 “rb+”      读写打开一个二进制文件,允许读和写 “wb+”      读写打开或建立一个二进制文件,允许读和写 “ab+”      读写打开一个二进制文件,允许读,或在文件末追加数据 对于文件使用方式有以下几点说明: 1. 文件使用方式由r,w,a,t,b,+六个字符拼成,各字符的含义是: r(read): 读 w(write): 写 a(append): 追加 t(text): 文本文件,可省略不写 b(banary): 二进制文件 +: 读和写 2. 凡用“r”打开一个文件时,该文件必须已经存在, 且只能从该文件读出。 3. 用“w”打开的文件只能向该文件写入。 若打开的文件不存在,则以指定的文件名建立该文件,若打开的文件已经存在,则将该文件删去,重建一个新文件。 4. 若要向一个已存在的文件追加新的信息,只能用“a ”方式打开文件。但此时该文件必须是存在的,否则将会出错。 5. 在打开一个文件时,如果出错,fopen将返回一个空指针值NULL。在程序中可以用这一信息来判别是否完成打开文件的工作,并作相应的处理。因此常用以下程序段打开文件: if((fp=fopen("c:\\hzk16","rb")==NULL) { printf("\nerror on open c:\\hzk16 file!"); getch(); exit(1); }   这段程序的意义是,如果返回的指针为空,表示不能打开C盘根目录下的hzk16文件,则给出提示信息“error on open c:\ hzk16file!”,下一行getch()的功能是从键盘输入一个字符,但不在屏幕上显示。在这里,该行的作用是等待, 只有当用户从键盘敲任一键时,程序才继续执行, 因此用户可利用这个等待时间阅读出错提示。敲键后执行exit(1)退出程序。 6. 把一个文本文件读入内存时,要将ASCII码转换成二进制码, 而把文件以文本方式写入磁盘时,也要把二进制码转换成ASCII码,因此文本文件的读写要花费较多的转换时间。对二进制文件的读写不存在这种转换。 7. 标准输入文件(键盘),标准输出文件(显示器 ),标准出错输出(出错信息)是由系统打开的,可直接使用。文件关闭函数fclose文件一旦使用完毕,应用关闭文件函数把文件关闭, 以避免文件的数据丢失等错误。 fclose函数 调用的一般形式是: fclose(文件指针); 例如: fclose(fp); 正常完成关闭文件操作时,fclose函数返回值为0。如返回非零值则表示有错误发生。文件的读写对文件的读和写是最常用的文件操作。 在C语言中提供了多种文件读写的函数: ·字符读写函数 :fgetc和fputc ·字符串读写函数:fgets和fputs ·数据块读写函数:freed和fwrite ·格式化读写函数:fscanf和fprinf   下面分别予以介绍。使用以上函数都要求包含头文件stdio.h。字符读写函数fgetc和fputc字符读写函数是以字符(字节)为单位的读写函数。 每次可从文件读出或向文件写入一个字符。 一、读字符函数fgetc   fgetc函数的功能是从指定的文件中读一个字符,函数调用的形式为: 字符变量=fgetc(文件指针); 例如:ch=fgetc(fp);其意义是从打开的文件fp中读取一个字符并送入ch中。   对于fgetc函数的使用有以下几点说明: 1. 在fgetc函数调用中,读取的文件必须是以读或读写方式打开的。 2. 读取字符的结果也可以不向字符变量赋值,例如:fgetc(fp);但是读出的字符不能保存。 3. 在文件内部有一个位置指针。用来指向文件的当前读写字节。在文件打开时,该指针总是指向文件的第一个字节。使用fgetc 函数后, 该位置指针将向后移动一个字节。 因此可连续多次使用fgetc函数,读取多个字符。 应注意文件指针和文件内部的位置指针不是一回事。文件指针是指向整个文件的,须在程序中定义说明,只要不重新赋值,文件指针的值是不变的。文件内部的位置指针用以指示文件内部的当前读写位置,每读写一次,该指针均向后移动,它不需在程序中定义说明,而是由系统自动设置的。 [例10.1]读入文件e10-1.c,在屏幕上输出。 #include main() { FILE *fp; char ch; if((fp=fopen("e10_1.c","rt"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } ch=fgetc(fp); while (ch!=EOF) { putchar(ch); ch=fgetc(fp); } fclose(fp); }   本例程序的功能是从文件中逐个读取字符,在屏幕上显示。 程序定义了文件指针fp,以读文本文件方式打开文件“e10_1.c”, 并使fp指向该文件。如打开文件出错, 给出提示并退出程序。程序第12行先读出一个字符,然后进入循环, 只要读出的字符不是文件结束标志(每个文件末有一结束标志EOF)就把该字符显示在屏幕上,再读入下一字符。每读一次,文件内部的位置指针向后移动一个字符,文件结束时,该指针指向EOF。执行本程序将显示整个文件。 二、写字符函数fputc   fputc函数的功能是把一个字符写入指定的文件中,函数调用的 形式为: fputc(字符量,文件指针); 其中,待写入的字符量可以是字符常量或变量,例如:fputc('a',fp);其意义是把字符a写入fp所指向的文件中。   对于fputc函数的使用也要说明几点: 1. 被写入的文件可以用、写、读写,追加方式打开,用写或读写方式打开一个已存在的文件时将清除原有的文件内容,写入字符从文件首开始。如需保留原有文件内容,希望写入的字符以文件末开始存放,必须以追加方式打开文件。被写入的文件若不存在,则创建该文件。 2. 每写入一个字符,文件内部位置指针向后移动一个字节。 3. fputc函数有一个返回值,如写入成功则返回写入的字符, 否则返回一个EOF。可用此来判断写入是否成功。 [例10.2]从键盘输入一行字符,写入一个文件, 再把该文件内容读出显示在屏幕上。 #include main() { FILE *fp; char ch; if((fp=fopen("string","wt+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("input a string:\n"); ch=getchar(); while (ch!='\n') { fputc(ch,fp); ch=getchar(); } rewind(fp); ch=fgetc(fp); while(ch!=EOF) { putchar(ch); ch=fgetc(fp); } printf("\n"); fclose(fp); }   程序中第6行以读写文本文件方式打开文件string。程序第13行从键盘读入一个字符后进入循环,当读入字符不为回车符时, 则把该字符写入文件之中,然后继续从键盘读入下一字符。 每输入一个字符,文件内部位置指针向后移动一个字节。写入完毕, 该指针已指向文件末。如要把文件从头读出,须把指针移向文件头, 程序第19行rewind函数用于把fp所指文件的内部位置指针移到文件头。 第20至25行用于读出文件中的一行内容。 [例10.3]把命令行参数中的前一个文件名标识的文件, 复制到后一个文件名标识的文件中, 如命令行中只有一个文件名则把该文件写到标准输出文件(显示器)中。 #include main(int argc,char *argv[]) { FILE *fp1,*fp2; char ch; if(argc==1) { printf("have not enter file name strike any key exit"); getch(); exit(0); } if((fp1=fopen(argv[1],"rt"))==NULL) { printf("Cannot open %s\n",argv[1]); getch(); exit(1); } if(argc==2) fp2=stdout; else if((fp2=fopen(argv[2],"wt+"))==NULL) { printf("Cannot open %s\n",argv[1]); getch(); exit(1); } while((ch=fgetc(fp1))!=EOF) fputc(ch,fp2); fclose(fp1); fclose(fp2); }   本程序为带参的main函数。程序中定义了两个文件指针 fp1 和fp2,分别指向命令行参数中给出的文件。如命令行参数中没有给出文件名,则给出提示信息。程序第18行表示如果只给出一个文件名,则使fp2指向标准输出文件(即显示器)。程序第25行至28行用循环语句逐个读出文件1中的字符再送到文件2中。再次运行时,给出了一个文件名(由例10.2所建立的文件), 故输出给标准输出文件stdout,即在显示器上显示文件内容。第三次运行,给出了二个文件名,因此把string中的内容读出,写入到OK之中。可用DOS命令type显示OK的内容:字符串读写函数fgets和fputs 一、读字符串函数fgets函数的功能是从指定的文件中读一个字符串到字符数组中,函数调用的形式为: fgets(字符数组名,n,文件指针); 其中的n是一个正整数。表示从文件中读出的字符串不超过 n-1个字符。在读入的最后一个字符后加上串结束标志'\0'。例如:fgets(str,n,fp);的意义是从fp所指的文件中读出n-1个字符送入字符数组str中。 [例10.4]从e10_1.c文件中读入一个含10个字符的字符串。 #include main() { FILE *fp; char str[11]; if((fp=fopen("e10_1.c","rt"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } fgets(str,11,fp); printf("%s",str); fclose(fp); }   本例定义了一个字符数组str共11个字节,在以读文本文件方式打开文件e101.c后,从中读出10个字符送入str数组,在数组最后一个单元内将加上'\0',然后在屏幕上显示输出str数组。输出的十个字符正是例10.1程序的前十个字符。   对fgets函数有两点说明: 1. 在读出n-1个字符之前,如遇到了换行符或EOF,则读出结束。 2. fgets函数也有返回值,其返回值是字符数组的首地址。 二、写字符串函数fputs fputs函数的功能是向指定的文件写入一个字符串,其调用形式为: fputs(字符串,文件指针) 其中字符串可以是字符串常量,也可以是字符数组名, 或指针 变量,例如: fputs(“abcd“,fp); 其意义是把字符串“abcd”写入fp所指的文件之中。[例10.5]在例10.2中建立的文件string中追加一个字符串。 #include main() { FILE *fp; char ch,st[20]; if((fp=fopen("string","at+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("input a string:\n"); scanf("%s",st); fputs(st,fp); rewind(fp); ch=fgetc(fp); while(ch!=EOF) { putchar(ch); ch=fgetc(fp); } printf("\n"); fclose(fp); }   本例要求在string文件末加写字符串,因此,在程序第6行以追加读写文本文件的方式打开文件string 。 然后输入字符串, 并用fputs函数把该串写入文件string。在程序15行用rewind函数把文件内部位置指针移到文件首。 再进入循环逐个显示当前文件中的全部内容。 数据块读写函数fread和fwrite   C语言还提供了用于整块数据的读写函数。 可用来读写一组数据,如一个数组元素,一个结构变量的值等。读数据块函数调用的一般形式为: fread(buffer,size,count,fp); 写数据块函数调用的一般形式为: fwrite(buffer,size,count,fp); 其中buffer是一个指针,在fread函数中,它表示存放输入数据的首地址。在fwrite函数中,它表示存放输出数据的首地址。 size 表示数据块的字节数。count 表示要读写的数据块块数。fp 表示文件指针。 例如: fread(fa,4,5,fp); 其意义是从fp所指的文件中,每次读4个字节(一个实数)送入实数组fa中,连续读5次,即读5个实数到fa中。 [例10.6]从键盘输入两个学生数据,写入一个文件中, 再读出这两个学生的数据显示在屏幕上。 #include struct stu { char name[10]; int num; int age; char addr[15]; }boya[2],boyb[2],*pp,*qq; main() { FILE *fp; char ch; int i; pp=boya; qq=boyb; if((fp=fopen("stu_list","wb+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("\ninput data\n"); for(i=0;i<2;i++,pp++) scanf("%s%d%d%s",pp->name,&pp->num,&pp->age,pp->addr); pp=boya; fwrite(pp,sizeof(struct stu),2,fp); rewind(fp); fread(qq,sizeof(struct stu),2,fp); printf("\n\nname\tnumber age addr\n"); for(i=0;i<2;i++,qq++) printf("%s\t%5d%7d%s\n",qq->name,qq->num,qq->age,qq->addr); fclose(fp); }   本例程序定义了一个结构stu,说明了两个结构数组boya和 boyb以及两个结构指针变量pp和qq。pp指向boya,qq指向boyb。程序第16行以读写方式打开二进制文件“stu_list”,输入二个学生数据之后,写入该文件中, 然后把文件内部位置指针移到文件首,读出两块学生数据后,在屏幕上显示。 格式化读写函数fscanf和fprintf fscanf函数,fprintf函数与前面使用的scanf和printf 函数的功能相似,都是格式化读写函数。 两者的区别在于 fscanf 函数和fprintf函数的读写对象不是键盘和显示器,而是磁盘文件。这两个函数的调用格式为: fscanf(文件指针,格式字符串,输入表列); fprintf(文件指针,格式字符串,输出表列); 例如: fscanf(fp,"%d%s",&i,s); fprintf(fp,"%d%c",j,ch); 用fscanf和fprintf函数也可以完成例10.6的问题。修改后的程序如例10.7所示。 [例10.7] #include struct stu { char name[10]; int num; int age; char addr[15]; }boya[2],boyb[2],*pp,*qq; main() { FILE *fp; char ch; int i; pp=boya; qq=boyb; if((fp=fopen("stu_list","wb+"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } printf("\ninput data\n"); for(i=0;i<2;i++,pp++) scanf("%s%d%d%s",pp->name,&pp->num,&pp->age,pp->addr); pp=boya; for(i=0;i<2;i++,pp++) fprintf(fp,"%s %d %d %s\n",pp->name,pp->num,pp->age,pp-> addr); rewind(fp); for(i=0;i<2;i++,qq++) fscanf(fp,"%s %d %d %s\n",qq->name,&qq->num,&qq->age,qq->addr); printf("\n\nname\tnumber age addr\n"); qq=boyb; for(i=0;i<2;i++,qq++) printf("%s\t%5d %7d %s\n",qq->name,qq->num, qq->age, qq->addr); fclose(fp); }   与例10.6相比,本程序中fscanf和fprintf函数每次只能读写一个结构数组元素,因此采用了循环语句来读写全部数组元素。 还要注意指针变量pp,qq由于循环改变了它们的值,因此在程序的25和32行分别对它们重新赋予了数组的首地址。 文件的随机读写   前面介绍的对文件的读写方式都是顺序读写, 即读写文件只能从头开始,顺序读写各个数据。 但在实际问题中常要求只读写文件中某一指定的部分。 为了解决这个问题可移动文件内部的位置指针到需要读写的位置,再进行读写,这种读写称为随机读写。 实现随机读写的关键是要按要求移动位置指针,这称为文件的定位。文件定位移动文件内部位置指针的函数主要有两个, 即 rewind 函数和fseek函数。   rewind函数前面已多次使用过,其调用形式为: rewind(文件指针); 它的功能是把文件内部的位置指针移到文件首。 下面主要介绍 fseek函数。   fseek函数用来移动文件内部位置指针,其调用形式为: fseek(文件指针,位移量,起始点); 其中:“文件指针”指向被移动的文件。 “位移量”表示移动的字节数,要求位移量是long型数据,以便在文件长度大于64KB 时不会出错。当用常量表示位移量时,要求加后缀“L”。“起始点”表示从何处开始计算位移量,规定的起始点有三种:文件首,当前位置和文件尾。 其表示方法如表10.2。 起始点    表示符号    数字表示 ────────────────────────── 文件首    SEEK—SET    0 当前位置   SEEK—CUR    1 文件末尾   SEEK—END     2 例如: fseek(fp,100L,0);其意义是把位置指针移到离文件首100个字节处。还要说明的是fseek函数一般用于二进制文件。在文本文件中由于要进行转换,故往往计算的位置会出现错误。文件的随机读写在移动位置指针之后, 即可用前面介绍的任一种读写函数进行读写。由于一般是读写一个数据据块,因此常用fread和fwrite函数。下面用例题来说明文件的随机读写。 [例10.8]在学生文件stu list中读出第二个学生的数据。 #include struct stu { char name[10]; int num; int age; char addr[15]; }boy,*qq; main() { FILE *fp; char ch; int i=1; qq=&boy; if((fp=fopen("stu_list","rb"))==NULL) { printf("Cannot open file strike any key exit!"); getch(); exit(1); } rewind(fp); fseek(fp,i*sizeof(struct stu),0); fread(qq,sizeof(struct stu),1,fp); printf("\n\nname\tnumber age addr\n"); printf("%s\t%5d %7d %s\n",qq->name,qq->num,qq->age, qq->addr); }   文件stu_list已由例10.6的程序建立,本程序用随机读出的方法读出第二个学生的数据。程序中定义boy为stu类型变量,qq为指向boy的指针。以读二进制文件方式打开文件,程序第22行移动文件位置指针。其中的i值为1,表示从文件头开始,移动一个stu类型的长度, 然后再读出的数据即为第二个学生的数据。 文件检测函数 C语言中常用的文件检测函数有以下几个。 一、文件结束检测函数feof函数调用格式: feof(文件指针); 功能:判断文件是否处于文件结束位置,如文件结束,则返回值为1,否则为0。 二、读写文件出错检测函数ferror函数调用格式: ferror(文件指针); 功能:检查文件在用各种输入输出函数进行读写时是否出错。 如ferror返回值为0表示未出错,否则表示有错。 三、文件出错标志和文件结束标志置0函数clearerr函数调用格式: clearerr(文件指针); 功能:本函数用于清除出错标志和文件结束标志,使它们为0值。 C库文件 C系统提供了丰富的系统文件,称为库文件,C的库文件分为两类,一类是扩展名为".h"的文件,称为头文件, 在前面的包含命令中我们已多次使用过。在".h"文件中包含了常量定义、 类型定义、宏定义、函数原型以及各种编译选择设置等信息。另一类是函数库,包括了各种函数的目标代码,供用户在程序中调用。 通常在程序中调用一个库函数时,要在调用之前包含该函数原型所在的".h" 文件。 在附录中给出了全部库函数。 ALLOC.H    说明内存管理函数(分配、释放等)。 ASSERT.H    定义 assert调试宏。 BIOS.H     说明调用IBM—PC ROM BIOS子程序的各个函数。 CONIO.H    说明调用DOS控制台I/O子程序的各个函数。 CTYPE.H    包含有关字符分类及转换的名类信息(如 isalpha和toascii等)。 DIR.H     包含有关目录和路径的结构、宏定义和函数。 DOS.H     定义和说明MSDOS和8086调用的一些常量和函数。 ERRON.H    定义错误代码的助记符。 FCNTL.H    定义在与open库子程序连接时的符号常量。 FLOAT.H    包含有关浮点运算的一些参数和函数。 GRAPHICS.H   说明有关图形功能的各个函数,图形错误代码的常量定义,正对不同驱动程序的各种颜色值,及函数用到的一些特殊结构。 IO.H      包含低级I/O子程序的结构和说明。 LIMIT.H    包含各环境参数、编译时间限制、数的范围等信息。 MATH.H     说明数学运算函数,还定了 HUGE VAL 宏, 说明了matherr和matherr子程序用到的特殊结构。 MEM.H     说明一些内存操作函数(其中大多数也在STRING.H 中说明)。 PROCESS.H   说明进程管理的各个函数,spawn…和EXEC …函数的结构说明。 SETJMP.H    定义longjmp和setjmp函数用到的jmp buf类型, 说明这两个函数。 SHARE.H    定义文件共享函数的参数。 SIGNAL.H    定义SIG[ZZ(Z] [ZZ)]IGN和SIG[ZZ(Z] [ZZ)]DFL常量,说明rajse和signal两个函数。 STDARG.H    定义读函数参数表的宏。(如vprintf,vscarf函数)。 STDDEF.H    定义一些公共数据类型和宏。 STDIO.H    定义Kernighan和Ritchie在Unix System V 中定义的标准和扩展的类型和宏。还定义标准I/O 预定义流:stdin,stdout和stderr,说明 I/O流子程序。 STDLIB.H    说明一些常用的子程序:转换子程序、搜索/ 排序子程序等。 STRING.H    说明一些串操作和内存操作函数。 SYS\STAT.H   定义在打开和创建文件时用到的一些符号常量。 SYS\TYPES.H  说明ftime函数和timeb结构。 SYS\TIME.H   定义时间的类型time[ZZ(Z] [ZZ)]t。 TIME.H     定义时间转换子程序asctime、localtime和gmtime的结构,ctime、 difftime、 gmtime、 localtime和stime用到的类型,并提供这些函数的原型。 VALUE.H    定义一些重要常量, 包括依赖于机器硬件的和为与Unix System V相兼容而说明的一些常量,包括浮点和双精度值的范围。 本章小结 1. C系统把文件当作一个“流”,按字节进行处理。 2. C文件按编码方式分为二进制文件和ASCII文件。 3. C语言中,用文件指针标识文件,当一个文件被 打开时, 可取得该文件指针。 4. 文件在读写之前必须打开,读写结束必须关闭。 5. 文件可按只读、只写、读写、追加四种操作方式打开,同时还必须指定文件的类型是二进制文件还是文本文件。 6. 文件可按字节,字符串,数据块为单位读写,文件也可按指定的格式进行读写。 7. 文件内部的位置指针可指示当前的读写位置,移动该指针可以对文件实现随机读写。 函数大全(a开头) 函数名: abort 功 能: 异常终止一个进程 用 法: void abort(void); 程序例: #include #include int main(void) { printf("Calling abort()\n"); abort(); return 0; /* This is never reached */ } 函数名: abs 功 能: 求整数的绝对值 用 法: int abs(int i); 程序例: #include #include int main(void) { int number = -1234; printf("number: %d absolute value: %d\n", number, abs(number)); return 0; } 函数名: absread, abswirte 功 能: 绝对磁盘扇区读、写数据 用 法: int absread(int drive, int nsects, int sectno, void *buffer); int abswrite(int drive, int nsects, in tsectno, void *buffer); 程序例: /* absread example */ #include #include #include #include int main(void) { int i, strt, ch_out, sector; char buf[512]; printf("Insert a diskette into drive A and press any key\n"); getch(); sector = 0; if (absread(0, 1, sector, &buf) != 0) { perror("Disk problem"); exit(1); } printf("Read OK\n"); strt = 3; for (i=0; i<80; i++) { ch_out = buf[strt+i]; putchar(ch_out); } printf("\n"); return(0); } 函数名: access 功 能: 确定文件的访问权限 用 法: int access(const char *filename, int amode); 程序例: #include #include int file_exists(char *filename); int main(void) { printf("Does NOTEXIST.FIL exist: %s\n", file_exists("NOTEXISTS.FIL") ? "YES" : "NO"); return 0; } int file_exists(char *filename) { return (access(filename, 0) == 0); } 函数名: acos 功 能: 反余弦函数 用 法: double acos(double x); 程序例: #include #include int main(void) { double result; double x = 0.5; result = acos(x); printf("The arc cosine of %lf is %lf\n", x, result); return 0; } 函数名: allocmem 功 能: 分配DOS存储段 用 法: int allocmem(unsigned size, unsigned *seg); 程序例: #include #include #include int main(void) { unsigned int size, segp; int stat; size = 64; /* (64 x 16) = 1024 bytes */ stat = allocmem(size, &segp); if (stat == -1) printf("Allocated memory at segment: %x\n", segp); else printf("Failed: maximum number of paragraphs available is %u\n", stat); return 0; } 函数名: arc 功 能: 画一弧线 用 法: void far arc(int x, int y, int stangle, int endangle, int radius); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int stangle = 45, endangle = 135; int radius = 100; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw arc */ arc(midx, midy, stangle, endangle, radius); /* clean up */ getch(); closegraph(); return 0; } 函数名: asctime 功 能: 转换日期和时间为ASCII码 用 法: char *asctime(const struct tm *tblock); 程序例: #include #include #include int main(void) { struct tm t; char str[80]; /* sample loading of tm structure */ t.tm_sec = 1; /* Seconds */ t.tm_min = 30; /* Minutes */ t.tm_hour = 9; /* Hour */ t.tm_mday = 22; /* Day of the Month */ t.tm_mon = 11; /* Month */ t.tm_year = 56; /* Year - does not include century */ t.tm_wday = 4; /* Day of the week */ t.tm_yday = 0; /* Does not show in asctime */ t.tm_isdst = 0; /* Is Daylight SavTime; does not show in asctime */ /* converts structure to null terminated string */ strcpy(str, asctime(&t)); printf("%s\n", str); return 0; } 函数名: asin 功 能: 反正弦函数 用 法: double asin(double x); 程序例: #include #include int main(void) { double result; double x = 0.5; result = asin(x); printf("The arc sin of %lf is %lf\n", x, result); return(0); } 函数名: assert 功 能: 测试一个条件并可能使程序终止 用 法: void assert(int test); 程序例: #include #include #include struct ITEM { int key; int value; }; /* add item to list, make sure list is not null */ void additem(struct ITEM *itemptr) { assert(itemptr != NULL); /* add item to list */ } int main(void) { additem(NULL); return 0; } 函数名: atan 功 能: 反正切函数 用 法: double atan(double x); 程序例: #include #include int main(void) { double result; double x = 0.5; result = atan(x); printf("The arc tangent of %lf is %lf\n", x, result); return(0); } 函数名: atan2 功 能: 计算Y/X的反正切值 用 法: double atan2(double y, double x); 程序例: #include #include int main(void) { double result; double x = 90.0, y = 45.0; result = atan2(y, x); printf("The arc tangent ratio of %lf is %lf\n", (y / x), result); return 0; } 函数名: atexit 功 能: 注册终止函数 用 法: int atexit(atexit_t func); 程序例: #include #include void exit_fn1(void) { printf("Exit function #1 called\n"); } void exit_fn2(void) { printf("Exit function #2 called\n"); } int main(void) { /* post exit function #1 */ atexit(exit_fn1); /* post exit function #2 */ atexit(exit_fn2); return 0; } 函数名: atof 功 能: 把字符串转换成浮点数 用 法: double atof(const char *nptr); 程序例: #include #include int main(void) { float f; char *str = "12345.67"; f = atof(str); printf("string = %s float = %f\n", str, f); return 0; } 函数名: atoi 功 能: 把字符串转换成长整型数 用 法: int atoi(const char *nptr); 程序例: #include #include int main(void) { int n; char *str = "12345.67"; n = atoi(str); printf("string = %s integer = %d\n", str, n); return 0; } 函数名: atol 功 能: 把字符串转换成长整型数 用 法: long atol(const char *nptr); 程序例: #include #include int main(void) { long l; char *str = "98765432"; l = atol(lstr); printf("string = %s integer = %ld\n", str, l); return(0); } 函数大全(b开头) 函数名: bar 功 能: 画一个二维条形图 用 法: void far bar(int left, int top, int right, int bottom); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, i; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through the fill patterns */ for (i=SOLID_FILL; i { /* set the fill style */ setfillstyle(i, getmaxcolor()); /* draw the bar */ bar(midx-50, midy-50, midx+50, midy+50); getch(); } /* clean up */ closegraph(); return 0; } 函数名: bar3d 功 能: 画一个三维条形图 用 法: void far bar3d(int left, int top, int right, int bottom, int depth, int topflag); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, i; /* initialize graphics, local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through the fill patterns */ for (i=EMPTY_FILL; i { /* set the fill style */ setfillstyle(i, getmaxcolor()); /* draw the 3-d bar */ bar3d(midx-50, midy-50, midx+50, midy+50, 10, 1); getch(); } /* clean up */ closegraph(); return 0; } 函数名: bdos 功 能: DOS系统调用 用 法: int bdos(int dosfun, unsigned dosdx, unsigned dosal); 程序例: #include #include /* Get current drive as 'A', 'B', ... */ char current_drive(void) { char curdrive; /* Get current disk as 0, 1, ... */ curdrive = bdos(0x19, 0, 0); return('A' + curdrive); } int main(void) { printf("The current drive is %c:\n", current_drive()); return 0; } 函数名: bdosptr 功 能: DOS系统调用 用 法: int bdosptr(int dosfun, void *argument, unsigned dosal); 程序例: #include #include #include #include #include #include #define BUFLEN 80 int main(void) { char buffer[BUFLEN]; int test; printf("Enter full pathname of a directory\n"); gets(buffer); test = bdosptr(0x3B,buffer,0); if(test) { printf("DOS error message: %d\n", errno); /* See errno.h for error listings */ exit (1); } getcwd(buffer, BUFLEN); printf("The current directory is: %s\n", buffer); return 0; } 函数名: bioscom 功 能: 串行I/O通信 用 法: int bioscom(int cmd, char abyte, int port); 程序例: #include #include #define COM1 0 #define DATA_READY 0x100 #define TRUE 1 #define FALSE 0 #define SETTINGS ( 0x80 | 0x02 | 0x00 | 0x00) int main(void) { int in, out, status, DONE = FALSE; bioscom(0, SETTINGS, COM1); cprintf("... BIOSCOM [ESC] to exit ...\n"); while (!DONE) { status = bioscom(3, 0, COM1); if (status & DATA_READY) if ((out = bioscom(2, 0, COM1) & 0x7F) != 0) putch(out); if (kbhit()) { if ((in = getch()) == '\x1B') DONE = TRUE; bioscom(1, in, COM1); } } return 0; } 函数名: biosdisk 功 能: 软硬盘I/O 用 法: int biosdisk(int cmd, int drive, int head, int track, int sector int nsects, void *buffer); 程序例: #include #include int main(void) { int result; char buffer[512]; printf("Testing to see if drive a: is ready\n"); result = biosdisk(4,0,0,0,0,1,buffer); result &= 0x02; (result) ? (printf("Drive A: Ready\n")) : (printf("Drive A: Not Ready\n")); return 0; } 函数名: biosequip 功 能: 检查设备 用 法: int biosequip(void); 程序例: #include #include int main(void) { int result; char buffer[512]; printf("Testing to see if drive a: is ready\n"); result = biosdisk(4,0,0,0,0,1,buffer); result &= 0x02; (result) ? (printf("Drive A: Ready\n")) : (printf("Drive A: Not Ready\n")); return 0; } 函数名: bioskey 功 能: 直接使用BIOS服务的键盘接口 用 法: int bioskey(int cmd); 程序例: #include #include #include #define RIGHT 0x01 #define LEFT 0x02 #define CTRL 0x04 #define ALT 0x08 int main(void) { int key, modifiers; /* function 1 returns 0 until a key is pressed */ while (bioskey(1) == 0); /* function 0 returns the key that is waiting */ key = bioskey(0); /* use function 2 to determine if shift keys were used */ modifiers = bioskey(2); if (modifiers) { printf("["); if (modifiers & RIGHT) printf("RIGHT"); if (modifiers & LEFT) printf("LEFT"); if (modifiers & CTRL) printf("CTRL"); if (modifiers & ALT) printf("ALT"); printf("]"); } /* print out the character read */ if (isalnum(key & 0xFF)) printf("'%c'\n", key); else printf("%#02x\n", key); return 0; } 函数名: biosmemory 功 能: 返回存储块大小 用 法:int biosmemory(void); 程序例: #include #include int main(void) { int memory_size; memory_size = biosmemory(); /* returns value up to 640K */ printf("RAM size = %dK\n",memory_size); return 0; } 函数名: biosprint 功 能: 直接使用BIOS服务的打印机I/O 用 法: int biosprint(int cmd, int byte, int port); 程序例: #include #include #include int main(void) { #define STATUS 2 /* printer status command */ #define PORTNUM 0 /* port number for LPT1 */ int status, abyte=0; printf("Please turn off your printer. Press any key to continue\n"); getch(); status = biosprint(STATUS, abyte, PORTNUM); if (status & 0x01) printf("Device time out.\n"); if (status & 0x08) printf("I/O error.\n"); if (status & 0x10) printf("Selected.\n"); if (status & 0x20) printf("Out of paper.\n"); if (status & 0x40) printf("Acknowledge.\n"); if (status & 0x80) printf("Not busy.\n"); return 0; } 函数名: biostime 功 能: 读取或设置BIOS时间 用 法: long biostime(int cmd, long newtime); 程序例: #include #include #include #include int main(void) { long bios_time; clrscr(); cprintf("The number of clock ticks since midnight is:\r\n"); cprintf("The number of seconds since midnight is:\r\n"); cprintf("The number of minutes since midnight is:\r\n"); cprintf("The number of hours since midnight is:\r\n"); cprintf("\r\nPress any key to quit:"); while(!kbhit()) { bios_time = biostime(0, 0L); gotoxy(50, 1); cprintf("%lu", bios_time); gotoxy(50, 2); cprintf("%.4f", bios_time / CLK_TCK); gotoxy(50, 3); cprintf("%.4f", bios_time / CLK_TCK / 60); gotoxy(50, 4); cprintf("%.4f", bios_time / CLK_TCK / 3600); } return 0; } 函数名: brk 功 能: 改变数据段空间分配 用 法: int brk(void *endds); 程序例: #include #include int main(void) { char *ptr; printf("Changing allocation with brk()\n"); ptr = malloc(1); printf("Before brk() call: %lu bytes free\n", coreleft()); brk(ptr+1000); printf(" After brk() call: %lu bytes free\n", coreleft()); return 0; } 函数名: bsearch 功 能: 二分法搜索 用 法: void *bsearch(const void *key, const void *base, size_t *nelem, size_t width, int(*fcmp)(const void *, const *)); 程序例: #include #include #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0])) int numarray[] = {123, 145, 512, 627, 800, 933}; int numeric (const int *p1, const int *p2) { return(*p1 - *p2); } int lookup(int key) { int *itemptr; /* The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at compile time */ itemptr = bsearch (&key, numarray, NELEMS(numarray), sizeof(int), (int(*)(const void *,const void *))numeric); return (itemptr != NULL); } int main(void) { if (lookup(512)) printf("512 is in the table.\n"); else printf("512 isn't in the table.\n"); return 0; } 函数大全(c开头) 函数名: cabs 功 能: 计算复数的绝对值 用 法: double cabs(struct complex z); 程序例: #include #include int main(void) { struct complex z; double val; z.x = 2.0; z.y = 1.0; val = cabs(z); printf("The absolute value of %.2lfi %.2lfj is %.2lf", z.x, z.y, val); return 0; } 函数名: calloc 功 能: 分配主存储器 用 法: void *calloc(size_t nelem, size_t elsize); 程序例: #include #include int main(void) { char *str = NULL; /* allocate memory for string */ str = calloc(10, sizeof(char)); /* copy "Hello" into string */ strcpy(str, "Hello"); /* display string */ printf("String is %s\n", str); /* free memory */ free(str); return 0; } 函数名: ceil 功 能: 向上舍入 用 法: double ceil(double x); 程序例: #include #include int main(void) { double number = 123.54; double down, up; down = floor(number); up = ceil(number); printf("original number %5.2lf\n", number); printf("number rounded down %5.2lf\n", down); printf("number rounded up %5.2lf\n", up); return 0; } 函数名: cgets 功 能: 从控制台读字符串 用 法: char *cgets(char *str); 程序例: #include #include int main(void) { char buffer[83]; char *p; /* There's space for 80 characters plus the NULL terminator */ buffer[0] = 81; printf("Input some chars:"); p = cgets(buffer); printf("\ncgets read %d characters: \"%s\"\n", buffer[1], p); printf("The returned pointer is %p, buffer[0] is at %p\n", p, &buffer); /* Leave room for 5 characters plus the NULL terminator */ buffer[0] = 6; printf("Input some chars:"); p = cgets(buffer); printf("\ncgets read %d characters: \"%s\"\n", buffer[1], p); printf("The returned pointer is %p, buffer[0] is at %p\n", p, &buffer); return 0; } 函数名: chdir 功 能: 改变工作目录 用 法: int chdir(const char *path); 程序例: #include #include #include char old_dir[MAXDIR]; char new_dir[MAXDIR]; int main(void) { if (getcurdir(0, old_dir)) { perror("getcurdir()"); exit(1); } printf("Current directory is: \\%s\n", old_dir); if (chdir("\\")) { perror("chdir()"); exit(1); } if (getcurdir(0, new_dir)) { perror("getcurdir()"); exit(1); } printf("Current directory is now: \\%s\n", new_dir); printf("\nChanging back to orignal directory: \\%s\n", old_dir); if (chdir(old_dir)) { perror("chdir()"); exit(1); } return 0; } 函数名: _chmod, chmod 功 能: 改变文件的访问方式 用 法: int chmod(const char *filename, int permiss); 程序例: #include #include #include void make_read_only(char *filename); int main(void) { make_read_only("NOTEXIST.FIL"); make_read_only("MYFILE.FIL"); return 0; } void make_read_only(char *filename) { int stat; stat = chmod(filename, S_IREAD); if (stat) printf("Couldn't make %s read-only\n", filename); else printf("Made %s read-only\n", filename); } 函数名: chsize 功 能: 改变文件大小 用 法: int chsize(int handle, long size); 程序例: #include #include #include int main(void) { int handle; char buf[11] = "0123456789"; /* create text file containing 10 bytes */ handle = open("DUMMY.FIL", O_CREAT); write(handle, buf, strlen(buf)); /* truncate the file to 5 bytes in size */ chsize(handle, 5); /* close the file */ close(handle); return 0; } 函数名: circle 功 能: 在给定半径以(x, y)为圆心画圆 用 法: void far circle(int x, int y, int radius); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int radius = 100; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw the circle */ circle(midx, midy, radius); /* clean up */ getch(); closegraph(); return 0; } 函数名: cleardevice 功 能: 清除图形屏幕 用 法: void far cleardevice(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* for centering screen messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* output a message to the screen */ outtextxy(midx, midy, "press any key to clear the screen:"); /* wait for a key */ getch(); /* clear the screen */ cleardevice(); /* output another message */ outtextxy(midx, midy, "press any key to quit:"); /* clean up */ getch(); closegraph(); return 0; } 函数名: clearerr 功 能: 复位错误标志 用 法:void clearerr(FILE *stream); 程序例: #include int main(void) { FILE *fp; char ch; /* open a file for writing */ fp = fopen("DUMMY.FIL", "w"); /* force an error condition by attempting to read */ ch = fgetc(fp); printf("%c\n",ch); if (ferror(fp)) { /* display an error message */ printf("Error reading from DUMMY.FIL\n"); /* reset the error and EOF indicators */ clearerr(fp); } fclose(fp); return 0; } 函数名: clearviewport 功 能: 清除图形视区 用 法: void far clearviewport(void); 程序例: #include #include #include #include #define CLIP_ON 1 /* activates clipping in viewport */ int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int ht; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } setcolor(getmaxcolor()); ht = textheight("W"); /* message in default full-screen viewport */ outtextxy(0, 0, "* <-- (0, 0) in default viewport"); /* create a smaller viewport */ setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON); /* display some messages */ outtextxy(0, 0, "* <-- (0, 0) in smaller viewport"); outtextxy(0, 2*ht, "Press any key to clear viewport:"); /* wait for a key */ getch(); /* clear the viewport */ clearviewport(); /* output another message */ outtextxy(0, 0, "Press any key to quit:"); /* clean up */ getch(); closegraph(); return 0; } 函数名: _close, close 功 能: 关闭文件句柄 用 法: int close(int handle); 程序例: #include #include #include #include main() { int handle; char buf[11] = "0123456789"; /* create a file containing 10 bytes */ handle = open("NEW.FIL", O_CREAT); if (handle > -1) { write(handle, buf, strlen(buf)); /* close the file */ close(handle); } else { printf("Error opening file\n"); } return 0; } 函数名: clock 功 能: 确定处理器时间 用 法: clock_t clock(void); 程序例: #include #include #include int main(void) { clock_t start, end; start = clock(); delay(2000); end = clock(); printf("The time was: %f\n", (end - start) / CLK_TCK); return 0; } 函数名: closegraph 功 能: 关闭图形系统 用 法: void far closegraph(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int x, y; /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "Press a key to close the graphics system:"); /* wait for a key */ getch(); /* closes down the graphics system */ closegraph(); printf("We're now back in text mode.\n"); printf("Press any key to halt:"); getch(); return 0; } 函数名: clreol 功 能: 在文本窗口中清除字符到行末 用 法: void clreol(void); 程序例: #include int main(void) { clrscr(); cprintf("The function CLREOL clears all characters from the\r\n"); cprintf("cursor position to the end of the line within the\r\n"); cprintf("current text window, without moving the cursor.\r\n"); cprintf("Press any key to continue . . ."); gotoxy(14, 4); getch(); clreol(); getch(); return 0; } 函数名: clrscr 功 能: 清除文本模式窗口 用 法: void clrscr(void); 程序例: #include int main(void) { int i; clrscr(); for (i = 0; i < 20; i++) cprintf("%d\r\n", i); cprintf("\r\nPress any key to clear screen"); getch(); clrscr(); cprintf("The screen has been cleared!"); getch(); return 0; } 函数名: coreleft 功 能: 返回未使用内存的大小 用 法: unsigned coreleft(void); 程序例: #include #include int main(void) { printf("The difference between the highest allocated block and\n"); printf("the top of the heap is: %lu bytes\n", (unsigned long) coreleft()); return 0; } 函数名: cos 功 能: 余弦函数 用 法: double cos(double x); 程序例: #include #include int main(void) { double result; double x = 0.5; result = cos(x); printf("The cosine of %lf is %lf\n", x, result); return 0; } 函数名: cosh 功 能: 双曲余弦函数 用 法: dluble cosh(double x); 程序例: #include #include int main(void) { double result; double x = 0.5; result = cosh(x); printf("The hyperboic cosine of %lf is %lf\n", x, result); return 0; } 函数名: country 功 能: 返回与国家有关的信息 用 法: struct COUNTRY *country(int countrycode, struct country *country); 程序例: #include #include #define USA 0 int main(void) { struct COUNTRY country_info; country(USA, &country_info); printf("The currency symbol for the USA is: %s\n", country_info.co_curr); return 0; } 函数名: cprintf 功 能: 送格式化输出至屏幕 用 法: int cprintf(const char *format[, argument, ...]); 程序例: #include int main(void) { /* clear the screen */ clrscr(); /* create a text window */ window(10, 10, 80, 25); /* output some text in the window */ cprintf("Hello world\r\n"); /* wait for a key */ getch(); return 0; } 函数名: cputs 功 能: 写字符到屏幕 用 法: void cputs(const char *string); 程序例: #include int main(void) { /* clear the screen */ clrscr(); /* create a text window */ window(10, 10, 80, 25); /* output some text in the window */ cputs("This is within the window\r\n"); /* wait for a key */ getch(); return 0; } 函数名: _creat creat 功 能: 创建一个新文件或重写一个已存在的文件 用 法: int creat (const char *filename, int permiss); 程序例: #include #include #include #include int main(void) { int handle; char buf[11] = "0123456789"; /* change the default file mode from text to binary */ _fmode = O_BINARY; /* create a binary file for reading and writing */ handle = creat("DUMMY.FIL", S_IREAD | S_IWRITE); /* write 10 bytes to the file */ write(handle, buf, strlen(buf)); /* close the file */ close(handle); return 0; } 函数名: creatnew 功 能: 创建一个新文件 用 法: int creatnew(const char *filename, int attrib); 程序例: #include #include #include #include #include int main(void) { int handle; char buf[11] = "0123456789"; /* attempt to create a file that doesn't already exist */ handle = creatnew("DUMMY.FIL", 0); if (handle == -1) printf("DUMMY.FIL already exists.\n"); else { printf("DUMMY.FIL successfully created.\n"); write(handle, buf, strlen(buf)); close(handle); } return 0; } 函数名: creattemp 功 能: 创建一个新文件或重写一个已存在的文件 用 法: int creattemp(const char *filename, int attrib); 程序例: #include #include #include int main(void) { int handle; char pathname[128]; strcpy(pathname, "\\"); /* create a unique file in the root directory */ handle = creattemp(pathname, 0); printf("%s was the unique file created.\n", pathname); close(handle); return 0; } 函数名: cscanf 功 能: 从控制台执行格式化输入 用 法: int cscanf(char *format[,argument, ...]); 程序例: #include int main(void) { char string[80]; /* clear the screen */ clrscr(); /* Prompt the user for input */ cprintf("Enter a string with no spaces:"); /* read the input */ cscanf("%s", string); /* display what was read */ cprintf("\r\nThe string entered is: %s", string); return 0; } 函数名: ctime 功 能: 把日期和时间转换为字符串 用 法: char *ctime(const time_t *time); 程序例: #include #include int main(void) { time_t t; time(&t); printf("Today's date and time: %s\n", ctime(&t)); return 0; } 函数名: ctrlbrk 功 能: 设置Ctrl-Break处理程序 用 法: void ctrlbrk(*fptr)(void); 程序例: #include #include #define ABORT 0 int c_break(void) { printf("Control-Break pressed. Program aborting ...\n"); return (ABORT); } int main(void) { ctrlbrk(c_break); for(;;) { printf("Looping... Press to quit:\n"); } return 0; } 函数大全(d开头) 函数名: delay 功 能: 将程序的执行暂停一段时间(毫秒) 用 法: void delay(unsigned milliseconds); 程序例: /* Emits a 440-Hz tone for 500 milliseconds */ #include int main(void) { sound(440); delay(500); nosound(); return 0; } 函数名: delline 功 能: 在文本窗口中删去一行 用 法: void delline(void); 程序例: #include int main(void) { clrscr(); cprintf("The function DELLINE deletes \ the line containing the\r\n"); cprintf("cursor and moves all lines \ below it one line up.\r\n"); cprintf("DELLINE operates within the \ currently active text\r\n"); cprintf("window. Press any key to \ continue . . ."); gotoxy(1,2); /* Move the cursor to the second line and first column */ getch(); delline(); getch(); return 0; } 函数名: detectgraph 功 能: 通过检测硬件确定图形驱动程序和模式 用 法: void far detectgraph(int far *graphdriver, int far *graphmode); 程序例: #include #include #include #include /* names of the various cards supported */ char *dname[] = { "requests detection", "a CGA", "an MCGA", "an EGA", "a 64K EGA", "a monochrome EGA", "an IBM 8514", "a Hercules monochrome", "an AT&T 6300 PC", "a VGA", "an IBM 3270 PC" }; int main(void) { /* returns detected hardware info. */ int gdriver, gmode, errorcode; /* detect graphics hardware available */ detectgraph(&gdriver, &gmode); /* read result of detectgraph call */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", \ grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* display the information detected */ clrscr(); printf("You have %s video display \ card.\n", dname[gdriver]); printf("Press any key to halt:"); getch(); return 0; } 函数名: difftime 功 能: 计算两个时刻之间的时间差 用 法: double difftime(time_t time2, time_t time1); 程序例: #include #include #include #include int main(void) { time_t first, second; clrscr(); first = time(NULL); /* Gets system time */ delay(2000); /* Waits 2 secs */ second = time(NULL); /* Gets system time again */ printf("The difference is: %f \ seconds\n",difftime(second,first)); getch(); return 0; } 函数名: disable 功 能: 屏蔽中断 用 法: void disable(void); 程序例: /***NOTE: This is an interrupt service routine. You cannot compile this program with Test Stack Overflow turned on and get an executable file that operates correctly. */ #include #include #include #define INTR 0X1C /* The clock tick interrupt */ void interrupt ( *oldhandler)(void); int count=0; void interrupt handler(void) { /* disable interrupts during the handling of the interrupt */ disable(); /* increase the global counter */ count++; /* reenable interrupts at the end of the handler */ enable(); /* call the old routine */ oldhandler(); } int main(void) { /* save the old interrupt vector */ oldhandler = getvect(INTR); /* install the new interrupt handler */ setvect(INTR, handler); /* loop until the counter exceeds 20 */ while (count < 20) printf("count is %d\n",count); /* reset the old interrupt handler */ setvect(INTR, oldhandler); return 0; } 函数名: div 功 能: 将两个整数相除, 返回商和余数 用 法: div_t (int number, int denom); 程序例: #include #include div_t x; int main(void) { x = div(10,3); printf("10 div 3 = %d remainder %d\n", x.quot, x.rem); return 0; } 函数名: dosexterr 功 能: 获取扩展DOS错误信息 用 法: int dosexterr(struct DOSERR *dblkp); 程序例: #include #include int main(void) { FILE *fp; struct DOSERROR info; fp = fopen("perror.dat","r"); if (!fp) perror("Unable to open file for reading"); dosexterr(&info); printf("Extended DOS error \ information:\n"); printf(" Extended error: \ %d\n",info.exterror); printf(" Class: \ %x\n",info.class); printf(" Action: \ %x\n",info.action); printf(" Error Locus: \ %x\n",info.locus); return 0; } 函数名: dostounix 功 能: 转换日期和时间为UNIX时间格式 用 法: long dostounix(struct date *dateptr, struct time *timeptr); 程序例: #include #include #include #include int main(void) { time_t t; struct time d_time; struct date d_date; struct tm *local; getdate(&d_date); gettime(&d_time); t = dostounix(&d_date, &d_time); local = localtime(&t); printf("Time and Date: %s\n", \ asctime(local)); return 0; } 函数名: drawpoly 功 能: 画多边形 用 法: void far drawpoly(int numpoints, int far *polypoints); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; /* our polygon array */ int poly[10]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", \ grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } maxx = getmaxx(); maxy = getmaxy(); poly[0] = 20; /* 1st vertext */ poly[1] = maxy / 2; poly[2] = maxx - 20; /* 2nd */ poly[3] = 20; poly[4] = maxx - 50; /* 3rd */ poly[5] = maxy - 20; poly[6] = maxx / 2; /* 4th */ poly[7] = maxy / 2; /* drawpoly doesn't automatically close the polygon, so we close it. */ poly[8] = poly[0]; poly[9] = poly[1]; /* draw the polygon */ drawpoly(5, poly); /* clean up */ getch(); closegraph(); return 0; } 函数名: dup 功 能: 复制一个文件句柄 用 法: int dup(int handle); 程序例: #include #include #include #include void flush(FILE *stream); int main(void) { FILE *fp; char msg[] = "This is a test"; /* create a file */ fp = fopen("DUMMY.FIL", "w"); /* write some data to the file */ fwrite(msg, strlen(msg), 1, fp); clrscr(); printf("Press any key to flush \ DUMMY.FIL:"); getch(); /* flush the data to DUMMY.FIL without closing it */ flush(fp); printf("\nFile was flushed, Press any \ key to quit:"); getch(); return 0; } void flush(FILE *stream) { int duphandle; /* flush TC's internal buffer */ fflush(stream); /* make a duplicate file handle */ duphandle = dup(fileno(stream)); /* close the duplicate handle to flush the DOS buffer */ close(duphandle); } 函数名: dup2 功 能: 复制文件句柄 用 法: int dup2(int oldhandle, int newhandle); 程序例: #include #include #include #include int main(void) { #define STDOUT 1 int nul, oldstdout; char msg[] = "This is a test"; /* create a file */ nul = open("DUMMY.FIL", O_CREAT | O_RDWR, S_IREAD | S_IWRITE); /* create a duplicate handle for standard output */ oldstdout = dup(STDOUT); /* redirect standard output to DUMMY.FIL by duplicating the file handle onto the file handle for standard output. */ dup2(nul, STDOUT); /* close the handle for DUMMY.FIL */ close(nul); /* will be redirected into DUMMY.FIL */ write(STDOUT, msg, strlen(msg)); /* restore original standard output handle */ dup2(oldstdout, STDOUT); /* close duplicate handle for STDOUT */ close(oldstdout); return 0; } 函数大全(e开头) 函数名: ecvt 功 能: 把一个浮点数转换为字符串 用 法: char ecvt(double value, int ndigit, int *decpt, int *sign); 程序例: #include #include #include int main(void) { char *string; double value; int dec, sign; int ndig = 10; clrscr(); value = 9.876; string = ecvt(value, ndig, &dec, &sign); printf("string = %s dec = %d \ sign = %d\n", string, dec, sign); value = -123.45; ndig= 15; string = ecvt(value,ndig,&dec,&sign); printf("string = %s dec = %d sign = %d\n", string, dec, sign); value = 0.6789e5; /* scientific notation */ ndig = 5; string = ecvt(value,ndig,&dec,&sign); printf("string = %s dec = %d\ sign = %d\n", string, dec, sign); return 0; } 函数名: ellipse 功 能: 画一椭圆 用 法: void far ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int stangle = 0, endangle = 360; int xradius = 100, yradius = 50; /* initialize graphics, local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw ellipse */ ellipse(midx, midy, stangle, endangle, xradius, yradius); /* clean up */ getch(); closegraph(); return 0; } 函数名: enable 功 能: 开放硬件中断 用 法: void enable(void); 程序例: /* ** NOTE: This is an interrupt service routine. You can NOT compile this program with Test Stack Overflow turned on and get an executable file which will operate correctly. */ #include #include #include /* The clock tick interrupt */ #define INTR 0X1C void interrupt ( *oldhandler)(void); int count=0; void interrupt handler(void) { /* disable interrupts during the handling of the interrupt */ disable(); /* increase the global counter */ count++; /* re enable interrupts at the end of the handler */ enable(); /* call the old routine */ oldhandler(); } int main(void) { /* save the old interrupt vector */ oldhandler = getvect(INTR); /* install the new interrupt handler */ setvect(INTR, handler); /* loop until the counter exceeds 20 */ while (count < 20) printf("count is %d\n",count); /* reset the old interrupt handler */ setvect(INTR, oldhandler); return 0; } 函数名: eof 功 能: 检测文件结束 用 法: int eof(int *handle); 程序例: #include #include #include #include #include int main(void) { int handle; char msg[] = "This is a test"; char ch; /* create a file */ handle = open("DUMMY.FIL", O_CREAT | O_RDWR, S_IREAD | S_IWRITE); /* write some data to the file */ write(handle, msg, strlen(msg)); /* seek to the beginning of the file */ lseek(handle, 0L, SEEK_SET); /* reads chars from the file until hit EOF */ do { read(handle, &ch, 1); printf("%c", ch); } while (!eof(handle)); close(handle); return 0; } 函数名: exec... 功 能: 装入并运行其它程序的函数 用 法: int execl(char *pathname, char *arg0, arg1, ..., argn, NULL); int execle(char *pathname, char *arg0, arg1, ..., argn, NULL, char *envp[]); int execlp(char *pathname, char *arg0, arg1, .., NULL); int execple(char *pathname, char *arg0, arg1, ..., NULL, char *envp[]); int execv(char *pathname, char *argv[]); int execve(char *pathname, char *argv[], char *envp[]); int execvp(char *pathname, char *argv[]); int execvpe(char *pathname, char *argv[], char *envp[]); 程序例: /* execv example */ #include #include #include void main(int argc, char *argv[]) { int i; printf("Command line arguments:\n"); for (i=0; i printf("[%2d] : %s\n", i, argv[i]); printf("About to exec child with arg1 arg2 ...\n"); execv("CHILD.EXE", argv); perror("exec error"); exit(1); } 函数名: exit 功 能: 终止程序 用 法: void exit(int status); 程序例: #include #include #include int main(void) { int status; printf("Enter either 1 or 2\n"); status = getch(); /* Sets DOS errorlevel */ exit(status - '0'); /* Note: this line is never reached */ return 0; } 函数名: exp 功 能: 指数函数 用 法: double exp(double x); 程序例: #include #include int main(void) { double result; double x = 4.0; result = exp(x); printf("'e' raised to the power \ of %lf (e ^ %lf) = %lf\n", x, x, result); return 0; } 函数大全(f开头) double fabs(double x); 返回双精度x的绝对值。 void far *farcalloc(unsigned long nunits,unsigned long unitsz); 堆中给含有nu从远nits个元素的,每个元素占用unitsz个字节长的数组分配存贮区。 成功是返回指向新分配的内存块的指针;若存贮空间不够,返回NULL。 unsigned long farcoreleft(void); 返回远堆中未用存贮区的大小。 void farfree(void far *block); 释放远堆中以前所分配内存块。 void far *farmalloc(unsigned long nbytes); 从远堆分配长nbytes字节的内存块,返回新地址。 void far *farrealloc(void far *oldblock,unsigned long nbytes); 调整已分配的内存块的大小为nbytes。需要的话,可把块中的内容复制到新位置。要注意:所有的可用的RAM可被分配,大于64K的块可被分配。 远指针用于存取被分配的块。返回重新分配的内存块的地址。若存贮块重新分配失败,返回NULL。 struct fcb { char fcb_drive; /* 0 = default, 1 = A, 2 = B */ char fcb_name[8]; /* File name */ char fcb_ext[3]; /* File extension */ short fcb_curblk; /* Current block number */ short fcb_recsize; /* Logical record size in bytes */ long fcb_filsize; /* File size in bytes */ short fcb_date; /* Date file was last written */ char fcb_resv[10]; /* Reserved for DOS */ char fcb_currec; /* Current record in block */ long fcb_random; /* Random record number */ }; int fclose(FILE *stream); 关闭一个流。 成功返回0;失败是返回EOF。 int fcloseall(void); 关闭所有打开的流,除了stdin,stdout,stdprn,stderr和stdaux。 char *fcvt(double value,int ndig,int *dec,int *sign); 把浮点数转换成字符串,把浮点数value转换成长度为ndig的以空字符终结的字符串,返回一个指向这个字符串的指针,相对于串的开始处, 小数点的位置,由dec间接存贮,dec若为负值,表示小数点在返回的字符串的左边。返回的字符串本身不带小数点。如果value的符号为负,由sign指向的值非零;否则它是零。 FILE *fdopen(int handle,char *type); 把流与一个文件描述字相联系地打开。fdopen使流stream与一个从creat,dup,dup2或open得到的文件描述字相联系。流的类型type必须与打开文件描述字handle的模式相匹配。 类型字符串type可以是下列值之一: r,打开用于只读; w,创建用于写; a,打开用于写在原有内容后面,文件不存在时创建用于写; r+,打开已存在的文件用于更新(读和写); a+,添加打开,文件不存在时创建,在末尾更新。成功时返回新打开的流。出错时返回NULL。 int feof(FILE *stream); 测试所给stream的文件尾标记的宏。 若检测到文件尾标记EOF或Ctrl-z返回非零值;否则,返回0。 #include int ferror(FILE *stream); 测试给定流读写错误的宏。 若检测到给定流上的错误返回非0值。 struct ffblk { char ff_reserved[21]; char ff_attrib; unsigned ff_ftime; unsigned ff_fdate; long ff_fsize; char ff_name[13]; }; int fflush(FILE *stream); 清除输入流的缓冲区,使它仍然打开,并把输出流的缓冲区的内容写入它所联系的文件中。成功时返回0,出错时返回EOF。 int fgetc(FILE *stream); 从流中读取下一个字符。 成功是返回输入流中的下一个字符;至文件结束或出错时返回EOF。 int fgetchar(void); 从标准输入流中读取字符,时定义为getc(stdin)的宏。 返回输入流stdin中的下一个字符,它已被转换成为无符号扩展的整形值。遇到出错或文件结束时返回EOF。 int fgetpos(FILE stream,fpos_t *pos); 取得当前文件指针。 fgetpos把与stream相联系的文件指针的位置保存在pos所指的地方。 其中,类型fpos_t在stdio.h中定义为 typeddf long fpos_t; 成功时返回0;失败时,返回非0值。 char *fgets(char *s,int n,FILE *stream); 成行读。 从流stream读n-1个字符,或遇换行符'\n'为止,把读出的内容,存入s中。与gets不同,fgets在s未尾保留换行符。一个空字节被加入到s,用来标记串的结束。 成功时返回s所指的字符串;在出错或遇到文件结束时返回NULL。 long filelength(int handle); 返回与handle相联系的文件长度的字节数,出错时返回-1L。 int fileno(FILE *stream); 返回与stream相联系的文件描述字。 int fileno(FILE *stream); 返回与stream相联系的文件描述字。 enum fill_patterns { /* Fill patterns for get/setfillstyle */ 0 EMPTY_FILL, /* fills area in background color */ 1 SOLID_FILL, /* fills area in solid fill color */ 2 LINE_FILL, /* --- fill */ 3 LTSLASH_FILL, /* /// fill */ 4 SLASH_FILL, /* /// fill with thick lines */ 5 BKSLASH_FILL, /* \\\ fill with thick lines */ 6 LTBKSLASH_FILL, /* \\\ fill */ 7 HATCH_FILL, /* light hatch fill */ 8 XHATCH_FILL, /* heavy cross hatch fill */ 9 INTERLEAVE_FILL, /* interleaving line fill */ 10 WIDE_DOT_FILL, /* Widely spaced dot fill */ 11 CLOSE_DOT_FILL, /* Closely spaced dot fill */ 12 USER_FILL /* user defined fill */ void far fillellipse(int x,int y,int xradius,int yradius); 画一填充椭圆。 以(x,y)为中心,以xradius和yradius为水平和垂直半轴,用当前颜色画边线,画一椭圆,用当前填充颜色和填充方式填充。 int findfirst(const char *pathname,struct ffblk *ffblk,int attrib); 搜索磁盘目录。开始通过DOS系统调用0x4E对磁盘目录进行搜索。pathname中可含有要找的盘区路径文件名。 文件名中可含有通配符(如*或?)。如果找到了匹配的文件,把文件目录信息填入ffblk结构。 attrib是MS-DOS的文件属性字节,用于在搜索过程中选择符合条件的文件。 attrib可以是在dos.h中定义的下列可取值之一:FA_RDONLY,只读;FA_HIDDEN隐藏;FA_SYSTEM系统文件;FA_LABEL卷标;FA_DIREC,目录;FA_ARCH,档案.可参考>. 结构ffblk的格式如下: struct ffblk{ char ff_reserved[21}; /*由DOS保留*/ char ff_attrib; /*属性查找*/ int ff_ftime; /*文件时间*/ int f_fdate; /*文件日期*/ long ff_fsize; /*文件大小*/ char ff_name[13}; /*找到的文件名*/ 在成功的地找到了与搜索路径pathname相匹配的文件名后返回0;否则返回-1。 int findnext(xtruct ffblk *ffblk);继续按findfirst的pathname搜索磁盘目录。 成功地找到了与搜索路径pathname相匹配的后续文件名后返回0;否则返回-1。 void far floodfill(int x,int y, int border); 填充一个有界的区域。 double floor(double x); 返回〈=x的用双精度浮点数表示的最大整数。 int flushall(void); 清除所有缓冲区。 清除所有与打开输入流相联系的缓冲区,并把所有和打开输出流相联系的缓冲区的内容写入到各自的文件中,跟在flushall后面的读操作,从输入文件中读新数据到缓冲区中。 返回一个表示打开输入流和输出流总数的整数。 couble fmod (double x, double y); 返回x对y的模,即x/y的余数。 void fnmerge(char *path,const char *drive,const char *dir,const char *name,const char *ext); 由给定的盘区路径文件名扩展名等组成部分建立path。 如果drive给出X:,dir给出\DIR\SUBDIR\,name给出NAME,和.ext给出.EXT,根据给定的组成部分,可建立一个完整的盘区路径文件名path为: X:\DIR\CUBDIR\NAME.EXT int fnsplit(const char *path,char *drive,char *cir,char *name,char *ext); 可把由path给出的盘区路径文件名扩展名分解成为各自的组成部分.返回一整型数. FILE*fopen (const char *filemane,const char *mode); 打开文件filemane返回相联系的流;出错返回NULL。 mode字符串的可取值有:r,打开用于读;w,打开用于写;a,打开用于在原有内容之后写;r+,打开已存在的文件用于更新(读和写);w+创建新文件用于更新;a+,打开用于在原有内容之后更新,若文件不存在就创建。 unsigned FP_OFF(void far *farptr); 返回远指针farptr的地址偏移量。 int fprintf(FILE *stream,const char *format[,argument,...]); 照原样抄写格式串format的内容到流stream中,每遇到一个%,就按规定的格式,依次输出一个表达式argument的值到流stream中,返回写的字符个数。出错时返回EOF。 FILE *stream; void main( void ) { long l; float fp; char s[81]; char c; stream = fopen( "fscanf.txt", "w+" ); if( stream == NULL ) printf( "The file fscanf.out was not opened\n" ); else {fprintf( stream, "%s %ld %f%c", "a-string",65000, 3.14159, 'x' ); /* Set pointer to beginning of file: */ fseek( stream, 0L, SEEK_SET ); /* Read data back from file: */ fscanf( stream, "%s", s ); fscanf( stream, "%ld", &l ); fscanf( stream, "%f", fscanf( stream, "%c", &c );/* Output data read: */ printf( "%s\n", s ); printf( "%ld\n", l ); printf( "%f\n", fp ); printf( "%c\n", c ); fclose( stream ); } } int fputc(int c,FILE *stream); 写一个字符到流中。 成功时返回所写的字符,失败或出错时返回EOF。 int fputchar(int c); 送一个字符到屏幕。 等价于fputc(c,stdout);成功时返回所写的字符,失败或出错时返回EOF。 int fputs(const char *s,FILE *stream); 把s所指的以空字符终结的字符串送入流中,不加换行符'\n',不拷贝串结束符'\0'。 成功时返回最后的字符,出错时返回EOF。 size_t fread(void *ptr,size_t size,size_t n,FILE *stream); 从所给的输入流stream中读取的n项数据,每一项数据长度为size字节,到由ptr所指的块中。 成功时返回所读的数据项数(不是字节数);遇到文件结束或出错时可能返回0。 void free(void *block); 释放先前分配的首地址为block的内存块。 int freemem(unsigned segx); 释放先前由allocmem分配的段地址为segx的内存块。 FILE *freopen(const char *filename,const char *mode,FILE *stream); 用filename所指定的文件代替打开的流stream所指定的文件。返回stream,出错时返回NULL。 double frexp(double x int *exponent); 将x分解成尾数合指数。 将给出的双精度数x分解成为在0.5和1之间尾数m和整形的指数n,使原来的x=m*(2的n次方),将整形指数n存入exponent所指的地址中,返回尾数m。 int fscan(FILE *stream,char *format,address,...); fscanf扫描输入字段,从流stream读入,每读入一个字段,就依次按照由format所指的格式串中取一个从%开始的格式进行格式化之后存入对应的一个地址address中。 返回成功地扫描,转换和存贮输入字段的个数,遇文件结束返回EOF。 FILE *stream; void main( void ) { long l; float fp; char s[81]; char c; stream = fopen( "fscanf.txt", "w+" ); if( stream == NULL ) printf( "The file fscanf.out was not opened\n" ); else {fprintf( stream, "%s %ld %f%c", "a-string",65000, 3.14159, 'x' ); /* Set pointer to beginning of file: */ fseek( stream, 0L, SEEK_SET ); /* Read data back from file: */ fscanf( stream, "%s", s ); fscanf( stream, "%ld", &l ); fscanf( stream, "%f", fscanf( stream, "%c", &c );/* Output data read: */ printf( "%s\n", s ); printf( "%ld\n", l ); printf( "%f\n", fp ); printf( "%c\n", c ); fclose( stream ); } } int fseek(FILE *stream,long offset,int whence); 在流上重新定位文件结构的位置。fseek设置与流stream相联系的文件指针到新的位置,新位置与whence给定的文件位置的距离为offset字节。 whence的取值必须是0,1或2中的一个,分别代表在stdio.h中定义的三个符号常量: 0是SEEK_SET,是文件开始位置; 1是SEEK_CUR,是当前的指针位置; 2时SEEK_END,是文件末尾。 调用了fseek之后,在更新的文件位置上,下一个操作可以是输入;也可以是输出。成功地移动了指针时,fseek返回0;出错或失败时返回非0值。 例: #include FILE *stream; void main( void ) { long l; float fp; char s[81]; char c; stream = fopen( "fscanf.txt", "w+" ); if( stream == NULL ) printf( "The file fscanf.out was not opened\n" ); else {fprintf( stream, "%s %ld %f%c", "a-string",65000, 3.14159, 'x' ); /* Set pointer to beginning of file: */ fseek( stream, 0L, SEEK_SET ); /* Read data back from file: */ fscanf( stream, "%s", s ); fscanf( stream, "%ld", &l ); fscanf( stream, "%f", fscanf( stream, "%c", &c );/* Output data read: */ printf( "%s\n", s ); printf( "%ld\n", l ); printf( "%f\n", fp ); printf( "%c\n", c ); fclose( stream ); } } int fsetpos(FILE *stream,const fpos_t *pos); fsetpos把与stream相联系的文件指针置于新的位置。这个新的位置是先前对此流调用fgetpos所得的值。 fsetpos清除stream所指文件的文件结束标志,并消除对该文件的所有ungetc操作。在调用fsetpos之后,文件的下一操作可以是输入或输出。 调用fsetpos成功时返回0;若失败,返回非0值。 int fstat(int handle,struct stat *statbuf); 把与handle相联系的打开文件或目录的信息存入到statbuf所指的定义在sys\stat.h中的stat结构中。成功时返回0;出错时返回-1。 long int ftell(FILE *stream); 返回流stream中当前文件指针位置。偏移量是文件开始算起的字节数。出错时返回-1L,是长整数的-1值。 void ftime(struct timeb *buf); 把当前时间存入到在sys\timeb.h中定义的timeb结构中。 size_t fwrite(const void *ptr,size_t size,size_t n,FILE *stream); fwrite从指针ptr开始把n个数据项添加到给定输出流stream,每个数据项的长度为size个字节。 成功是返回确切的数据项数(不是字节数);出错时返回短(short)计数值。可能是0。 函数大全(g开头) 函数名: gcvt 功 能: 把浮点数转换成字符串 用 法: char *gcvt(double value, int ndigit, char *buf); 程序例: #include #include int main(void) { char str[25]; double num; int sig = 5; /* significant digits */ /* a regular number */ num = 9.876; gcvt(num, sig, str); printf("string = %s\n", str); /* a negative number */ num = -123.4567; gcvt(num, sig, str); printf("string = %s\n", str); /* scientific notation */ num = 0.678e5; gcvt(num, sig, str); printf("string = %s\n", str); return(0); } 函数名: geninterrupt 功 能: 产生一个软中断 用 法: void geninterrupt(int intr_num); 程序例: #include #include /* function prototype */ void writechar(char ch); int main(void) { clrscr(); gotoxy(80,25); writechar('*'); getch(); return 0; } /* outputs a character at the current cursor position using the video BIOS to avoid the scrolling of the screen when writing to location (80,25). */ void writechar(char ch) { struct text_info ti; /* grab current text settings */ gettextinfo(&ti); /* interrupt 0x10 sub-function 9 */ _AH = 9; /* character to be output */ _AL = ch; _BH = 0; /* video page */ _BL = ti.attribute; /* video attribute */ _CX = 1; /* repetition factor */ geninterrupt(0x10); /* output the char */ } 函数名: getarccoords 功 能: 取得最后一次调用arc的坐标 用 法: void far getarccoords(struct arccoordstype far *arccoords); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct arccoordstype arcinfo; int midx, midy; int stangle = 45, endangle = 270; char sstr[80], estr[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } midx = getmaxx() / 2; midy = getmaxy() / 2; /* draw arc and get coordinates */ setcolor(getmaxcolor()); arc(midx, midy, stangle, endangle, 100); getarccoords(&arcinfo); /* convert arc information into strings */ sprintf(sstr, "*- (%d, %d)", arcinfo.xstart, arcinfo.ystart); sprintf(estr, "*- (%d, %d)", arcinfo.xend, arcinfo.yend); /* output the arc information */ outtextxy(arcinfo.xstart, arcinfo.ystart, sstr); outtextxy(arcinfo.xend, arcinfo.yend, estr); /* clean up */ getch(); closegraph(); return 0; } 函数名: getaspectratio 功 能: 返回当前图形模式的纵横比 用 法: void far getaspectratio(int far *xasp, int far *yasp); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int xasp, yasp, midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* get current aspect ratio settings */ getaspectratio(&xasp, &yasp); /* draw normal circle */ circle(midx, midy, 100); getch(); /* draw wide circle */ cleardevice(); setaspectratio(xasp/2, yasp); circle(midx, midy, 100); getch(); /* draw narrow circle */ cleardevice(); setaspectratio(xasp, yasp/2); circle(midx, midy, 100); /* clean up */ getch(); closegraph(); return 0; } 函数名: getbkcolor 功 能: 返回当前背景颜色 用 法: int far getbkcolor(void); 程序例: #include #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int bkcolor, midx, midy; char bkname[35]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* for centering text on the display */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* get the current background color */ bkcolor = getbkcolor(); /* convert color value into a string */ itoa(bkcolor, bkname, 10); strcat(bkname, " is the current background color."); /* display a message */ outtextxy(midx, midy, bkname); /* clean up */ getch(); closegraph(); return 0; } 函数名: getc 功 能: 从流中取字符 用 法: int getc(FILE *stream); 程序例: #include int main(void) { char ch; printf("Input a character:"); /* read a character from the standard input stream */ ch = getc(stdin); printf("The character input was: '%c'\n", ch); return 0; } 函数名: getcbrk 功 能: 获取Control_break设置 用 法: int getcbrk(void); 程序例: #include #include int main(void) { if (getcbrk()) printf("Cntrl-brk flag is on\n"); else printf("Cntrl-brk flag is off\n"); return 0; } 函数名: getch 功 能: 从控制台无回显地取一个字符 用 法: int getch(void); 程序例: #include #include int main(void) { char ch; printf("Input a character:"); ch = getche(); printf("\nYou input a '%c'\n", ch); return 0; } 函数名: getchar 功 能: 从stdin流中读字符 用 法: int getchar(void); 程序例: #include int main(void) { int c; /* Note that getchar reads from stdin and is line buffered; this means it will not return until you press ENTER. */ while ((c = getchar()) != '\n') printf("%c", c); return 0; } 函数名: getche 功 能: 从控制台取字符(带回显) 用 法: int getche(void); 程序例: #include #include int main(void) { char ch; printf("Input a character:"); ch = getche(); printf("\nYou input a '%c'\n", ch); return 0; } 函数名: getcolor 功 能: 返回当前画线颜色 用 法: int far getcolor(void); 程序例: #include #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int color, midx, midy; char colname[35]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* for centering text on the display */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* get the current drawing color */ color = getcolor(); /* convert color value into a string */ itoa(color, colname, 10); strcat(colname, " is the current drawing color."); /* display a message */ outtextxy(midx, midy, colname); /* clean up */ getch(); closegraph(); return 0; } 函数名: getcurdir 功 能: 取指定驱动器的当前目录 用 法: int getcurdir(int drive, char *direc); 程序例: #include #include #include char *current_directory(char *path) { strcpy(path, "X:\\"); /* fill string with form of response: X:\ */ path[0] = 'A' + getdisk(); /* replace X with current drive letter */ getcurdir(0, path+3); /* fill rest of string with current directory */ return(path); } int main(void) { char curdir[MAXPATH]; current_directory(curdir); printf("The current directory is %s\n", curdir); return 0; } 函数名: getcwd 功 能: 取当前工作目录 用 法: char *getcwd(char *buf, int n); 程序例: #include #include int main(void) { char buffer[MAXPATH]; getcwd(buffer, MAXPATH); printf("The current directory is: %s\n", buffer); return 0; } 函数名: getdate 功 能: 取DOS日期 用 法: void getdate(struct *dateblk); 程序例: #include #include int main(void) { struct date d; getdate(&d); printf("The current year is: %d\n", d.da_year); printf("The current day is: %d\n", d.da_day); printf("The current month is: %d\n", d.da_mon); return 0; } 函数名: getdefaultpalette 功 能: 返回调色板定义结构 用 法: struct palettetype *far getdefaultpalette(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int i; /* structure for returning palette copy */ struct palettetype far *pal=(void *) 0; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } setcolor(getmaxcolor()); /* return a pointer to the default palette */ pal = getdefaultpalette(); for (i=0; i<16; i++) { printf("colors[%d] = %d\n", i, pal->colors[i]); getch(); } /* clean up */ getch(); closegraph(); return 0; } 函数名: getdisk 功 能: 取当前磁盘驱动器号 用 法: int getdisk(void); 程序例: #include #include int main(void) { int disk; disk = getdisk() + 'A'; printf("The current drive is: %c\n", disk); return 0; } 函数名: getdrivername 功 能: 返回指向包含当前图形驱动程序名字的字符串指针 用 法: char *getdrivename(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* stores the device driver name */ char *drivername; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } setcolor(getmaxcolor()); /* get name of the device driver in use */ drivername = getdrivername(); /* for centering text on the screen */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* output the name of the driver */ outtextxy(getmaxx() / 2, getmaxy() / 2, drivername); /* clean up */ getch(); closegraph(); return 0; } 函数名: getdta 功 能: 取磁盘传输地址 用 法: char far *getdta(void); 程序例: #include #include int main(void) { char far *dta; dta = getdta(); printf("The current disk transfer \ address is: %Fp\n", dta); return 0; } 函数名: getenv 功 能: 从环境中取字符串 用 法: char *getenv(char *envvar); 程序例: #include #include int main(void) { char *s; s=getenv("COMSPEC"); /* get the comspec environment parameter */ printf("Command processor: %s\n",s); /* display comspec parameter */ return 0; } 函数名: getfat, getfatd 功 能: 取文件分配表信息 用 法: void getfat(int drive, struct fatinfo *fatblkp); 程序例: #include #include int main(void) { struct fatinfo diskinfo; int flag = 0; printf("Please insert disk in drive A\n"); getchar(); getfat(1, &diskinfo); /* get drive information */ printf("\nDrive A: is "); switch((unsigned char) diskinfo.fi_fatid) { case 0xFD: printf("360K low density\n"); break; case 0xF9: printf("1.2 Meg high density\n"); break; default: printf("unformatted\n"); flag = 1; } if (!flag) { printf(" sectors per cluster %5d\n", diskinfo.fi_sclus); printf(" number of clusters %5d\n", diskinfo.fi_nclus); printf(" bytes per sector %5d\n", diskinfo.fi_bysec); } return 0; } 函数名: getfillpattern 功 能: 将用户定义的填充模式拷贝到内存中 用 法: void far getfillpattern(char far *upattern); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; char pattern[8] = {0x00, 0x70, 0x20, 0x27, 0x25, 0x27, 0x04, 0x04}; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy(); setcolor(getmaxcolor()); /* select a user defined fill pattern */ setfillpattern(pattern, getmaxcolor()); /* fill the screen with the pattern */ bar(0, 0, maxx, maxy); getch(); /* get the current user defined fill pattern */ getfillpattern(pattern); /* alter the pattern we grabbed */ pattern[4] -= 1; pattern[5] -= 3; pattern[6] += 3; pattern[7] -= 4; /* select our new pattern */ setfillpattern(pattern, getmaxcolor()); /* fill the screen with the new pattern */ bar(0, 0, maxx, maxy); /* clean up */ getch(); closegraph(); return 0; } 函数名: getfillsettings 功 能: 取得有关当前填充模式和填充颜色的信息 用 法: void far getfillsettings(struct fillsettingstype far *fillinfo); 程序例: #include #include #include #include / the names of the fill styles supported */ char *fname[] = { "EMPTY_FILL", "SOLID_FILL", "LINE_FILL", "LTSLASH_FILL", "SLASH_FILL", "BKSLASH_FILL", "LTBKSLASH_FILL", "HATCH_FILL", "XHATCH_FILL", "INTERLEAVE_FILL", "WIDE_DOT_FILL", "CLOSE_DOT_FILL", "USER_FILL" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct fillsettingstype fillinfo; int midx, midy; char patstr[40], colstr[40]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get information about current fill pattern and color */ getfillsettings(&fillinfo); /* convert fill information into strings */ sprintf(patstr, "%s is the fill style.", fname[fillinfo.pattern]); sprintf(colstr, "%d is the fill color.", fillinfo.color); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, patstr); outtextxy(midx, midy+2*textheight("W"), colstr); /* clean up */ getch(); closegraph(); return 0; } 函数名: getftime 功 能: 取文件日期和时间 用 法: int getftime(int handle, struct ftime *ftimep); 程序例: #include #include int main(void) { FILE *stream; struct ftime ft; if ((stream = fopen("TEST.$$$", "wt")) == NULL) { fprintf(stderr, "Cannot open output file.\n"); return 1; } getftime(fileno(stream), &ft); printf("File time: %u:%u:%u\n", ft.ft_hour, ft.ft_min, ft.ft_tsec * 2); printf("File date: %u/%u/%u\n", ft.ft_month, ft.ft_day, ft.ft_year+1980); fclose(stream); return 0; } 函数名: getgraphmode 功 能: 返回当前图形模式 用 法: int far getgraphmode(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, mode; char numname[80], modename[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get mode number and name strings */ mode = getgraphmode(); sprintf(numname, "%d is the current mode number.", mode); sprintf(modename, "%s is the current graphics mode", getmodename(mode)); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, numname); outtextxy(midx, midy+2*textheight("W"), modename); /* clean up */ getch(); closegraph(); return 0; } 函数名: getftime 功 能: 取文件日期和时间 用 法: int getftime(int handle, struct ftime *ftimep); 程序例: #include #include int main(void) { FILE *stream; struct ftime ft; if ((stream = fopen("TEST.$$$", "wt")) == NULL) { fprintf(stderr, "Cannot open output file.\n"); return 1; } getftime(fileno(stream), &ft); printf("File time: %u:%u:%u\n", ft.ft_hour, ft.ft_min, ft.ft_tsec * 2); printf("File date: %u/%u/%u\n", ft.ft_month, ft.ft_day, ft.ft_year+1980); fclose(stream); return 0; } 函数名: getgraphmode 功 能: 返回当前图形模式 用 法: int far getgraphmode(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, mode; char numname[80], modename[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get mode number and name strings */ mode = getgraphmode(); sprintf(numname, "%d is the current mode number.", mode); sprintf(modename, "%s is the current graphics mode", getmodename(mode)); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, numname); outtextxy(midx, midy+2*textheight("W"), modename); /* clean up */ getch(); closegraph(); return 0; } 函数名: getimage 功 能: 将指定区域的一个位图存到主存中 用 法: void far getimage(int left, int top, int right, int bottom, void far *bitmap); 程序例: #include #include #include #include #include void save_screen(void far *buf[4]); void restore_screen(void far *buf[4]); int maxx, maxy; int main(void) { int gdriver=DETECT, gmode, errorcode; void far *ptr[4]; /* auto-detect the graphics driver and mode */ initgraph(&gdriver, &gmode, ""); errorcode = graphresult(); /* check for any errors */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } maxx = getmaxx(); maxy = getmaxy(); /* draw an image on the screen */ rectangle(0, 0, maxx, maxy); line(0, 0, maxx, maxy); line(0, maxy, maxx, 0); save_screen(ptr); /* save the current screen */ getch(); /* pause screen */ cleardevice(); /* clear screen */ restore_screen(ptr); /* restore the screen */ getch(); /* pause screen */ closegraph(); return 0; } void save_screen(void far *buf[4]) { unsigned size; int ystart=0, yend, yincr, block; yincr = (maxy+1) / 4; yend = yincr; size = imagesize(0, ystart, maxx, yend); /* get byte size of image */ for (block=0; block<=3; block++) { if ((buf[block] = farmalloc(size)) == NULL) { closegraph(); printf("Error: not enough heap space in save_screen().\n"); exit(1); } getimage(0, ystart, maxx, yend, buf[block]); ystart = yend + 1; yend += yincr + 1; } } void save_screen(void far *buf[4]) { unsigned size; int ystart=0, yend, yincr, block; yincr = (maxy+1) / 4; yend = yincr; size = imagesize(0, ystart, maxx, yend); /* get byte size of image */ for (block=0; block<=3; block++) { if ((buf[block] = farmalloc(size)) == NULL) { closegraph(); printf("Error: not enough heap space in save_screen().\n"); exit(1); } getimage(0, ystart, maxx, yend, buf[block]); ystart = yend + 1; yend += yincr + 1; } } void restore_screen(void far *buf[4]) { int ystart=0, yend, yincr, block; yincr = (maxy+1) / 4; yend = yincr; for (block=0; block<=3; block++) { putimage(0, ystart, buf[block], COPY_PUT); farfree(buf[block]); ystart = yend + 1; yend += yincr + 1; } } 函数名: getlinesettings 功 能: 取当前线型、模式和宽度 用 法: void far getlinesettings(struct linesettingstype far *lininfo): 程序例: #include #include #include #include /* the names of the line styles supported */ char *lname[] = { "SOLID_LINE", "DOTTED_LINE", "CENTER_LINE", "DASHED_LINE", "USERBIT_LINE" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct linesettingstype lineinfo; int midx, midy; char lstyle[80], lpattern[80], lwidth[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get information about current line settings */ getlinesettings(&lineinfo); /* convert line information into strings */ sprintf(lstyle, "%s is the line style.", lname[lineinfo.linestyle]); sprintf(lpattern, "0x%X is the user-defined line pattern.", lineinfo.upattern); sprintf(lwidth, "%d is the line thickness.", lineinfo.thickness); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, lstyle); outtextxy(midx, midy+2*textheight("W"), lpattern); outtextxy(midx, midy+4*textheight("W"), lwidth); /* clean up */ getch(); closegraph(); return 0; } 函数名: getmaxcolor 功 能: 返回可以传给函数setcolor的最大颜色值 用 法: int far getmaxcolor(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; char colstr[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* grab the color info. and convert it to a string */ sprintf(colstr, "This mode supports colors 0..%d", getmaxcolor()); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, colstr); /* clean up */ getch(); closegraph(); return 0; } 函数名: getmaxx 功 能: 返回屏幕的最大x坐标 用 法: int far getmaxx(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; char xrange[80], yrange[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* convert max resolution values into strings */ sprintf(xrange, "X values range from 0..%d", getmaxx()); sprintf(yrange, "Y values range from 0..%d", getmaxy()); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, xrange); outtextxy(midx, midy+textheight("W"), yrange); /* clean up */ getch(); closegraph(); return 0; } 函数名: getmaxy 功 能: 返回屏幕的最大y坐标 用 法: int far getmaxy(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; char xrange[80], yrange[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* convert max resolution values into strings */ sprintf(xrange, "X values range from 0..%d", getmaxx()); sprintf(yrange, "Y values range from 0..%d", getmaxy()); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, xrange); outtextxy(midx, midy+textheight("W"), yrange); /* clean up */ getch(); closegraph(); return 0; } 函数名: getmodename 功 能: 返回含有指定图形模式名的字符串指针 用 法: char *far getmodename(int mode_name); 程序例: #include #include #include #include int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, mode; char numname[80], modename[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get mode number and name strings */ mode = getgraphmode(); sprintf(numname, "%d is the current mode number.", mode); sprintf(modename, "%s is the current graphics mode.", getmodename(mode)); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, numname); outtextxy(midx, midy+2*textheight("W"), modename); /* clean up */ getch(); closegraph(); return 0; } 函数名: getmoderange 功 能: 取给定图形驱动程序的模式范围 用 法: void far getmoderange(int graphdriver, int far *lomode, int far *himode); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int low, high; char mrange[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get the mode range for this driver */ getmoderange(gdriver, &low, &high); /* convert mode range info. into strings */ sprintf(mrange, "This driver supports modes %d..%d", low, high); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, mrange); /* clean up */ getch(); closegraph(); return 0; } 函数名: getpalette 功 能: 返回有关当前调色板的信息 用 法: void far getpalette(struct palettetype far *palette); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct palettetype pal; char psize[80], pval[20]; int i, ht; int y = 10; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } /* grab a copy of the palette */ getpalette(&pal); /* convert palette info. into strings */ sprintf(psize, "The palette has %d \ modifiable entries.", pal.size); /* display the information */ outtextxy(0, y, psize); if (pal.size != 0) { ht = textheight("W"); y += 2*ht; outtextxy(0, y, "Here are the current \ values:"); y += 2*ht; for (i=0; i { sprintf(pval, "palette[%02d]: 0x%02X", i, pal.colors[i]); outtextxy(0, y, pval); } } /* clean up */ getch(); closegraph(); return 0; } 函数名: getpass 功 能: 读一个口令 用 法: char *getpass(char *prompt); 程序例: #include int main(void) { char *password; password = getpass("Input a password:"); cprintf("The password is: %s\r\n", password); return 0; } 函数名: getpixel 功 能: 取得指定像素的颜色 用 法: int far getpixel(int x, int y); 程序例: #include #include #include #include #include #define PIXEL_COUNT 1000 #define DELAY_TIME 100 /* in milliseconds */ int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int i, x, y, color, maxx, maxy, maxcolor, seed; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); /* terminate with an error code */ exit(1); } maxx = getmaxx() + 1; maxy = getmaxy() + 1; maxcolor = getmaxcolor() + 1; while (!kbhit()) { /* seed the random number generator */ seed = random(32767); srand(seed); for (i=0; i { x = random(maxx); y = random(maxy); color = random(maxcolor); putpixel(x, y, color); } delay(DELAY_TIME); srand(seed); for (i=0; i { x = random(maxx); y = random(maxy); color = random(maxcolor); if (color == getpixel) 函数名: gets 功 能: 从流中取一字符串 用 法: char *gets(char *string); 程序例: #include int main(void) { char string[80]; printf("Input a string:"); gets(string); printf("The string input was: %s\n", string); return 0; } 函数名: gettext 功 能: 将文本方式屏幕上的文本拷贝到存储区 用 法: int gettext(int left, int top, int right, int bottom, void *destin); 程序例: #include char buffer[4096]; int main(void) { int i; clrscr(); for (i = 0; i <= 20; i++) cprintf("Line #%d\r\n", i); gettext(1, 1, 80, 25, buffer); gotoxy(1, 25); cprintf("Press any key to clear screen..."); getch(); clrscr(); gotoxy(1, 25); cprintf("Press any key to restore screen..."); getch(); puttext(1, 1, 80, 25, buffer); gotoxy(1, 25); cprintf("Press any key to quit..."); getch(); return 0; } 函数名: gettextinfo 功 能: 取得文本模式的显示信息 用 法: void gettextinfo(struct text_info *inforec); 程序例: #include int main(void) { struct text_info ti; gettextinfo(&ti); cprintf("window left %2d\r\n",ti.winleft); cprintf("window top %2d\r\n",ti.wintop); cprintf("window right %2d\r\n",ti.winright); cprintf("window bottom %2d\r\n",ti.winbottom); cprintf("attribute %2d\r\n",ti.attribute); cprintf("normal attribute %2d\r\n",ti.normattr); cprintf("current mode %2d\r\n",ti.currmode); cprintf("screen height %2d\r\n",ti.screenheight); cprintf("screen width %2d\r\n",ti.screenwidth); cprintf("current x %2d\r\n",ti.curx); cprintf("current y %2d\r\n",ti.cury); return 0; } 函数名: gettextsettings 功 能: 返回有关当前图形文本字体的信息 用 法: void far gettextsettings(struct textsettingstype far *textinfo); 程序例: #include #include #include #include /* the names of the fonts supported */ char *font[] = { "DEFAULT_FONT", "TRIPLEX_FONT", "SMALL_FONT", "SANS_SERIF_FONT", "GOTHIC_FONT" }; /* the names of the text directions supported */ char *dir[] = { "HORIZ_DIR", "VERT_DIR" }; /* horizontal text justifications supported */ char *hjust[] = { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" }; /* vertical text justifications supported */ char *vjust[] = { "BOTTOM_TEXT", "CENTER_TEXT", "TOP_TEXT" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct textsettingstype textinfo; int midx, midy, ht; char fontstr[80], dirstr[80], sizestr[80]; char hjuststr[80], vjuststr[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get information about current text settings */ gettextsettings(&textinfo); /* convert text information into strings */ sprintf(fontstr, "%s is the text style.", font[textinfo.font]); sprintf(dirstr, "%s is the text direction.", dir[textinfo.direction]); sprintf(sizestr, "%d is the text size.", textinfo.charsize); sprintf(hjuststr, "%s is the horizontal justification.", hjust[textinfo.horiz]); sprintf(vjuststr, "%s is the vertical justification.", vjust[textinfo.vert]); /* display the information */ ht = textheight("W"); settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, fontstr); outtextxy(midx, midy+2*ht, dirstr); outtextxy(midx, midy+4*ht, sizestr); outtextxy(midx, midy+6*ht, hjuststr); outtextxy(midx, midy+8*ht, vjuststr); /* clean up */ getch(); closegraph(); return 0; } 函数名: gettime 功 能: 取得系统时间 用 法: void gettime(struct time *timep); 程序例: #include #include int main(void) { struct time t; gettime(&t); printf("The current time is: %2d:%02d:%02d.%02d\n", t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund); return 0; } 函数名: getvect 功 能: 取得中断向量入口 用 法: void interrupt(*getvect(int intr_num)); 程序例: #include #include void interrupt get_out(); /* interrupt prototype */ void interrupt (*oldfunc)(); /* interrupt function pointer */ int looping = 1; int main(void) { puts("Press to terminate"); /* save the old interrupt */ oldfunc = getvect(5); /* install interrupt handler */ setvect(5,get_out); /* do nothing */ while (looping); /* restore to original interrupt routine */ setvect(5,oldfunc); puts("Success"); return 0; } void interrupt get_out() { looping = 0; /* change global variable to get out of loop */ } 函数名: getverify 功 能: 返回DOS校验标志状态 用 法: int getverify(void); 程序例: #include #include int main(void) { if (getverify()) printf("DOS verify flag is on\n"); else printf("DOS verify flag is off\n"); return 0; } 函数名: getviewsetting 功 能: 返回有关当前视区的信息 用 法: void far getviewsettings(struct viewporttype far *viewport); 程序例: #include #include #include #include char *clip[] = { "OFF", "ON" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct viewporttype viewinfo; int midx, midy, ht; char topstr[80], botstr[80], clipstr[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* get information about current viewport */ getviewsettings(&viewinfo); /* convert text information into strings */ sprintf(topstr, "(%d, %d) is the upper left viewport corner.", viewinfo.left, viewinfo.top); sprintf(botstr, "(%d, %d) is the lower right viewport corner.", viewinfo.right, viewinfo.bottom); sprintf(clipstr, "Clipping is turned %s.", clip[viewinfo.clip]); /* display the information */ settextjustify(CENTER_TEXT, CENTER_TEXT); ht = textheight("W"); outtextxy(midx, midy, topstr); outtextxy(midx, midy+2*ht, botstr); outtextxy(midx, midy+4*ht, clipstr); /* clean up */ getch(); closegraph(); return 0; } 函数名: getw 功 能: 从流中取一整数 用 法: int getw(FILE *strem); 程序例: #include #include #define FNAME "test.$$$" int main(void) { FILE *fp; int word; /* place the word in a file */ fp = fopen(FNAME, "wb"); if (fp == NULL) { printf("Error opening file %s\n", FNAME); exit(1); } word = 94; putw(word,fp); if (ferror(fp)) printf("Error writing to file\n"); else printf("Successful write\n"); fclose(fp); /* reopen the file */ fp = fopen(FNAME, "rb"); if (fp == NULL) { printf("Error opening file %s\n", FNAME); exit(1); } /* extract the word */ word = getw(fp); if (ferror(fp)) printf("Error reading file\n"); else printf("Successful read: word = %d\n", word); /* clean up */ fclose(fp); unlink(FNAME); return 0; } 函数名: getx 功 能: 返回当前图形位置的x坐标 用 法: int far getx(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2, getmaxy() / 2); /* create a message string */ sprintf(msg, "<-(%d, %d) is the here.", getx(), gety()); /* display the message */ outtext(msg); /* clean up */ getch(); closegraph(); return 0; } 函数名: gety 功 能: 返回当前图形位置的y坐标 用 法: int far gety(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2, getmaxy() / 2); /* create a message string */ sprintf(msg, "<-(%d, %d) is the here.", getx(), gety()); /* display the message */ outtext(msg); /* clean up */ getch(); closegraph(); return 0; } 函数名: gmtime 功 能: 把日期和时间转换为格林尼治标准时间(GMT) 用 法: struct tm *gmtime(long *clock); 程序例: #include #include #include #include /* Pacific Standard Time & Daylight Savings */ char *tzstr = "TZ=PST8PDT"; int main(void) { time_t t; struct tm *gmt, *area; putenv(tzstr); tzset(); t = time(NULL); area = localtime(&t); printf("Local time is: %s", asctime(area)); gmt = gmtime(&t); printf("GMT is: %s", asctime(gmt)); return 0; } 函数名: gotoxy 功 能: 在文本窗口中设置光标 用 法: void gotoxy(int x, int y); 程序例: #include int main(void) { clrscr(); gotoxy(35, 12); cprintf("Hello world"); getch(); return 0; } 函数名: gotoxy 功 能: 在文本窗口中设置光标 用 法: void gotoxy(int x, int y); 程序例: #include int main(void) { clrscr(); gotoxy(35, 12); cprintf("Hello world"); getch(); return 0; } 函数名: graphdefaults 功 能: 将所有图形设置复位为它们的缺省值 用 法: void far graphdefaults(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, "c:\\bor\\Borland\\bgi"); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy(); /* output line with non-default settings */ setlinestyle(DOTTED_LINE, 0, 3); line(0, 0, maxx, maxy); outtextxy(maxx/2, maxy/3, "Before default values are restored."); getch(); /* restore default values for everything */ graphdefaults(); /* clear the screen */ cleardevice(); /* output line with default settings */ line(0, 0, maxx, maxy); outtextxy(maxx/2, maxy/3, "After restoring default values."); /* clean up */ getch(); closegraph(); return 0; } 函数名: grapherrormsg 功 能: 返回一个错误信息串的指针 用 法: char *far grapherrormsg(int errorcode); 程序例: #include #include #include #include #define NONSENSE -50 int main(void) { /* FORCE AN ERROR TO OCCUR */ int gdriver = NONSENSE, gmode, errorcode; /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* if an error occurred, then output a */ /* descriptive error message. */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } 函数名: graphresult 功 能: 返回最后一次不成功的图形操作的错误代码 用 法: int far graphresult(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } 函数名: _graphfreemem 功 能: 用户可修改的图形存储区释放函数 用 法: void far _graphfreemem(void far *ptr, unsigned size); 程序例: #include #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; /* clear the text screen */ clrscr(); printf("Press any key to initialize graphics mode:"); getch(); clrscr(); /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* display a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, "Press any key to exit graphics mode:"); /* clean up */ getch(); closegraph(); return 0; } /* called by the graphics kernel to allocate memory */ void far * far _graphgetmem(unsigned size) { printf("_graphgetmem called to allocate %d bytes.\n", size); printf("hit any key:"); getch(); printf("\n"); /* allocate memory from far heap */ return farmalloc(size); } /* called by the graphics kernel to free memory */ void far _graphfreemem(void far *ptr, unsigned size) { printf("_graphfreemem called to free %d bytes.\n", size); printf("hit any key:"); getch(); printf("\n"); /* free ptr from far heap */ farfree(ptr); } 函数名: _graphgetmem 功 能: 用户可修改的图形存储区分配函数 用 法: void far *far _graphgetmem(unsigned size); 程序例: #include #include #include #include #include int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; /* clear the text screen */ clrscr(); printf("Press any key to initialize graphics mode:"); getch(); clrscr(); /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* display a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(midx, midy, "Press any key to exit graphics mode:"); /* clean up */ getch(); closegraph(); return 0; } /* called by the graphics kernel to allocate memory */ void far * far _graphgetmem(unsigned size) { printf("_graphgetmem called to allocate %d bytes.\n", size); printf("hit any key:"); getch(); printf("\n"); /* allocate memory from far heap */ return farmalloc(size); } /* called by the graphics kernel to free memory */ void far _graphfreemem(void far *ptr, unsigned size) { printf("_graphfreemem called to free %d bytes.\n", size); printf("hit any key:"); getch(); printf("\n"); /* free ptr from far heap */ farfree(ptr); } 函数大全(h开头) 函数名: harderr 功 能: 建立一个硬件错误处理程序 用 法: void harderr(int (*fptr)()); 程序例: /*This program will trap disk errors and prompt the user for action. Try running it with no disk in drive A: to invoke its functions.*/ #include #include #include #define IGNORE 0 #define RETRY 1 #define ABORT 2 int buf[500]; /*define the error messages for trapping disk problems*/ static char *err_msg[] = { "write protect", "unknown unit", "drive not ready", "unknown command", "data error (CRC)", "bad request", "seek error", "unknown media type", "sector not found", "printer out of paper", "write fault", "read fault", "general failure", "reserved", "reserved", "invalid disk change" }; error_win(char *msg) { int retval; cputs(msg); /*prompt for user to press a key to abort, retry, ignore*/ while(1) { retval= getch(); if (retval == 'a' || retval == 'A') { retval = ABORT; break; } if (retval == 'r' || retval == 'R') { retval = RETRY; break; } if (retval == 'i' || retval == 'I') { retval = IGNORE; break; } } return(retval); } /*pragma warn -par reduces warnings which occur due to the non use of the parameters errval, bp and si to the handler.*/ #pragma warn -par int handler(int errval,int ax,int bp,int si) { static char msg[80]; unsigned di; int drive; int errorno; di= _DI; /*if this is not a disk error then it was another device having trouble*/ if (ax < 0) { /* report the error */ error_win("Device error"); /* and return to the program directly requesting abort */ hardretn(ABORT); } /* otherwise it was a disk error */ drive = ax & 0x00FF; errorno = di & 0x00FF; /* report which error it was */ sprintf(msg, "Error: %s on drive %c\r\nA)bort, R)etry, I)gnore: ", err_msg[errorno], 'A' + drive); /* return to the program via dos interrupt 0x23 with abort, retry, or ignore as input by the user. */ hardresume(error_win(msg)); return ABORT; } #pragma warn +par int main(void) { /* install our handler on the hardware problem interrupt */ harderr(handler); clrscr(); printf("Make sure there is no disk in drive A:\n"); printf("Press any key ....\n"); getch(); printf("Trying to access drive A:\n"); printf("fopen returned %p\n",fopen("A:temp.dat", "w")); return 0; } 函数名: hardresume 功 能: 硬件错误处理函数 用 法: void hardresume(int rescode); 程序例: /* This program will trap disk errors and prompt the user for action. */ /* Try running it with no disk in drive A: to invoke its functions */ #include #include #include #define IGNORE 0 #define RETRY 1 #define ABORT 2 int buf[500]; /* define the error messages for trapping disk problems */ static char *err_msg[] = { "write protect", "unknown unit", "drive not ready", "unknown command", "data error (CRC)", "bad request", "seek error", "unknown media type", "sector not found", "printer out of paper", "write fault", "read fault", "general failure", "reserved", "reserved", "invalid disk change" }; error_win(char *msg) { int retval; cputs(msg); /* prompt for user to press a key to abort, retry, ignore */ while(1) { retval= getch(); if (retval == 'a' || retval == 'A') { retval = ABORT; break; } if (retval == 'r' || retval == 'R') { retval = RETRY; break; } if (retval == 'i' || retval == 'I') { retval = IGNORE; break; } } return(retval); } /* pragma warn -par reduces warnings which occur due to the non use */ /* of the parameters errval, bp and si to the handler. */ #pragma warn -par int handler(int errval,int ax,int bp,int si) { static char msg[80]; unsigned di; int drive; int errorno; di= _DI; /* if this is not a disk error then it was another device having trouble */ if (ax < 0) { /* report the error */ error_win("Device error"); /* and return to the program directly requesting abort */ hardretn(ABORT); } /* otherwise it was a disk error */ drive = ax & 0x00FF; errorno = di & 0x00FF; /* report which error it was */ sprintf(msg, "Error: %s on drive %c\r\nA)bort, R)etry, I)gnore: ", err_msg[errorno], 'A' + drive); /* return to the program via dos interrupt 0x23 with abort, retry */ /* or ignore as input by the user. */ hardresume(error_win(msg)); return ABORT; } #pragma warn +par int main(void) { /* install our handler on the hardware problem interrupt */ harderr(handler); clrscr(); printf("Make sure there is no disk in drive A:\n"); printf("Press any key ....\n"); getch(); printf("Trying to access drive A:\n"); printf("fopen returned %p\n",fopen("A:temp.dat", "w")); return 0; } 函数名: highvideo 功 能: 选择高亮度文本字符 用 法: void highvideo(void); 程序例: #include int main(void) { clrscr(); lowvideo(); cprintf("Low Intensity text\r\n"); highvideo(); gotoxy(1,2); cprintf("High Intensity Text\r\n"); return 0; } 函数名: hypot 功 能: 计算直角三角形的斜边长 用 法: double hypot(double x, double y); 程序例: #include #include int main(void) { double result; double x = 3.0; double y = 4.0; result = hypot(x, y); printf("The hypotenuse is: %lf\n", result); return 0; } 函数大全(i开头) 函数名: imagesize 功 能: 返回保存位图像所需的字节数 用 法: unsigned far imagesize(int left, int top, int right, int bottom); 程序例: #include #include #include #include #define ARROW_SIZE 10 void draw_arrow(int x, int y); int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; void *arrow; int x, y, maxx; unsigned int size; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); x = 0; y = getmaxy() / 2; /* draw the image to be grabbed */ draw_arrow(x, y); /* calculate the size of the image */ size = imagesize(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE); /* allocate memory to hold the image */ arrow = malloc(size); /* grab the image */ getimage(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE, arrow); /* repeat until a key is pressed */ while (!kbhit()) { /* erase old image */ putimage(x, y-ARROW_SIZE, arrow, XOR_PUT); x += ARROW_SIZE; if (x >= maxx) x = 0; /* plot new image */ putimage(x, y-ARROW_SIZE, arrow, XOR_PUT); } /* clean up */ free(arrow); closegraph(); return 0; } void draw_arrow(int x, int y) { /* draw an arrow on the screen */ moveto(x, y); linerel(4*ARROW_SIZE, 0); linerel(-2*ARROW_SIZE, -1*ARROW_SIZE); linerel(0, 2*ARROW_SIZE); linerel(2*ARROW_SIZE, -1*ARROW_SIZE); } 函数名: initgraph 功 能: 初始化图形系统 用 法: void far initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* return with error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } 函数名: inport 功 能: 从硬件端口中输入 用 法: int inp(int protid); 程序例: #include #include int main(void) { int result; int port = 0; /* serial port 0 */ result = inport(port); printf("Word read from port %d = 0x%X\n", port, result); return 0; } 函数名: insline 功 能: 在文本窗口中插入一个空行 用 法: void insline(void); 程序例: #include int main(void) { clrscr(); cprintf("INSLINE inserts an empty line in the text window\r\n"); cprintf("at the cursor position using the current text\r\n"); cprintf("background color. All lines below the empty one\r\n"); cprintf("move down one line and the bottom line scrolls\r\n"); cprintf("off the bottom of the window.\r\n"); cprintf("\r\nPress any key to continue:"); gotoxy(1, 3); getch(); insline(); getch(); return 0; } 函数名: installuserdriver 功 能: 安装设备驱动程序到BGI设备驱动程序表中 用 法: int far installuserdriver(char far *name, int (*detect)(void)); 程序例: #include #include #include #include /* function prototypes */ int huge detectEGA(void); void checkerrors(void); int main(void) { int gdriver, gmode; /* install a user written device driver */ gdriver = installuserdriver("EGA", detectEGA); /* must force use of detection routine */ gdriver = DETECT; /* check for any installation errors */ checkerrors(); /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* check for any initialization errors */ checkerrors(); /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } /* detects EGA or VGA cards */ int huge detectEGA(void) { int driver, mode, sugmode = 0; detectgraph(&driver, &mode); if ((driver == EGA) || (driver == VGA)) /* return suggested video mode number */ return sugmode; else /* return an error code */ return grError; } /* check for and report any graphics errors */ void checkerrors(void) { int errorcode; /* read result of last graphics operation */ errorcode = graphresult(); if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } } 函数名: installuserfont 功 能: 安装未嵌入BGI系统的字体文件(CHR) 用 法: int far installuserfont(char far *name); 程序例: #include #include #include #include /* function prototype */ void checkerrors(void); int main(void) { /* request auto detection */ int gdriver = DETECT, gmode; int userfont; int midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); midx = getmaxx() / 2; midy = getmaxy() / 2; /* check for any initialization errors */ checkerrors(); /* install a user defined font file */ userfont = installuserfont("USER.CHR"); /* check for any installation errors */ checkerrors(); /* select the user font */ settextstyle(userfont, HORIZ_DIR, 4); /* output some text */ outtextxy(midx, midy, "Testing!"); /* clean up */ getch(); closegraph(); return 0; } /* check for and report any graphics errors */ void checkerrors(void) { int errorcode; /* read result of last graphics operation */ errorcode = graphresult(); if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } } 函数名: int86 功 能: 通用8086软中断接口 用 法: int int86(int intr_num, union REGS *inregs, union REGS *outregs); 程序例: #include #include #include #define VIDEO 0x10 void movetoxy(int x, int y) { union REGS regs; regs.h.ah = 2; /* set cursor postion */ regs.h.dh = y; regs.h.dl = x; regs.h.bh = 0; /* video page 0 */ int86(VIDEO, ?s, ?s); } int main(void) { clrscr(); movetoxy(35, 10); printf("Hello\n"); return 0; } 函数名: int86x 功 能: 通用8086软中断接口 用 法: int int86x(int intr_num, union REGS *insegs, union REGS *outregs, struct SREGS *segregs); 程序例: #include #include #include int main(void) { char filename[80]; union REGS inregs, outregs; struct SREGS segregs; printf("Enter filename: "); gets(filename); inregs.h.ah = 0x43; inregs.h.al = 0x21; inregs.x.dx = FP_OFF(filename); segregs.ds = FP_SEG(filename); int86x(0x21, &inregs, &outregs, &segregs); printf("File attribute: %X\n", outregs.x.cx); return 0; } 函数名: intdos 功 能: 通用DOS接口 用 法: int intdos(union REGS *inregs, union REGS *outregs); 程序例: #include #include /* deletes file name; returns 0 on success, nonzero on failure */ int delete_file(char near *filename) { union REGS regs; int ret; regs.h.ah = 0x41; /* delete file */ regs.x.dx = (unsigned) filename; ret = intdos(?s, ?s); /* if carry flag is set, there was an error */ return(regs.x.cflag ? ret : 0); } int main(void) { int err; err = delete_file("NOTEXIST.$$$"); if (!err) printf("Able to delete NOTEXIST.$$$\n"); else printf("Not Able to delete NOTEXIST.$$$\n"); return 0; } 函数名: intdosx 功 能: 通用DOS中断接口 用 法: int intdosx(union REGS *inregs, union REGS *outregs, struct SREGS *segregs); 程序例: #include #include /* deletes file name; returns 0 on success, nonzero on failure */ int delete_file(char far *filename) { union REGS regs; struct SREGS sregs; int ret; regs.h.ah = 0x41; /* delete file */ regs.x.dx = FP_OFF(filename); sregs.ds = FP_SEG(filename); ret = intdosx(?s, ?s, &sregs); /* if carry flag is set, there was an error */ return(regs.x.cflag ? ret : 0); } int main(void) { int err; err = delete_file("NOTEXIST.$$$"); if (!err) printf("Able to delete NOTEXIST.$$$\n"); else printf("Not Able to delete NOTEXIST.$$$\n"); return 0; } 函数名: intr 功 能: 改变软中断接口 用 法: void intr(int intr_num, struct REGPACK *preg); 程序例: #include #include #include #include #define CF 1 /* Carry flag */ int main(void) { char directory[80]; struct REGPACK reg; printf("Enter directory to change to: "); gets(directory); reg.r_ax = 0x3B << 8; /* shift 3Bh into AH */ reg.r_dx = FP_OFF(directory); reg.r_ds = FP_SEG(directory); intr(0x21, ?); if (reg.r_flags & CF) printf("Directory change failed\n"); getcwd(directory, 80); printf("The current directory is: %s\n", directory); return 0; } 函数名: ioctl 功 能: 控制I/O设备 用 法: int ioctl(int handle, int cmd[,int *argdx, int argcx]); 程序例: #include #include #include int main(void) { int stat; /* use func 8 to determine if the default drive is removable */ stat = ioctl(0, 8, 0, 0); if (!stat) printf("Drive %c is removable.\n", getdisk() + 'A'); else printf("Drive %c is not removable.\n", getdisk() + 'A'); return 0; } 函数名: isatty 功 能: 检查设备类型 用 法: int isatty(int handle); 程序例: #include #include int main(void) { int handle; handle = fileno(stdprn); if (isatty(handle)) printf("Handle %d is a device type\n", handle); else printf("Handle %d isn't a device type\n", handle); return 0; } 函数名: itoa 功 能: 把一整数转换为字符串 用 法: char *itoa(int value, char *string, int radix); 程序例: #include #include int main(void) { int number = 12345; char string[25]; itoa(number, string, 10); printf("integer = %d string = %s\n", number, string); return 0; } 函数大全(k开头) 函数名: kbhit 功 能: 检查当前按下的键 用 法: int kbhit(void); 程序例: #include int main(void) { cprintf("Press any key to continue:"); while (!kbhit()) /* do nothing */ ; cprintf("\r\nA key was pressed...\r\n"); return 0; } 函数名: keep 功 能: 退出并继续驻留 用 法: void keep(int status, int size); 程序例: /***NOTE: This is an interrupt service routine. You can NOT compile this program with Test Stack Overflow turned on and get an executable file which will operate correctly. Due to the nature of this function the formula used to compute the number of paragraphs may not necessarily work in all cases. Use with care! Terminate Stay Resident (TSR) programs are complex and no other support for them is provided. Refer to the MS-DOS technical documentation for more information. */ #include /* The clock tick interrupt */ #define INTR 0x1C /* Screen attribute (blue on grey) */ #define ATTR 0x7900 /* reduce heaplength and stacklength to make a smaller program in memory */ extern unsigned _heaplen = 1024; extern unsigned _stklen = 512; void interrupt ( *oldhandler)(void); void interrupt handler(void) { unsigned int (far *screen)[80]; static int count; /* For a color screen the video memory is at B800:0000. For a monochrome system use B000:000 */ screen = MK_FP(0xB800,0); /* increase the counter and keep it within 0 to 9 */ count++; count %= 10; /* put the number on the screen */ screen[0][79] = count + '0' + ATTR; /* call the old interrupt handler */ oldhandler(); } int main(void) { /* get the address of the current clock tick interrupt */ oldhandler = getvect(INTR); /* install the new interrupt handler */ setvect(INTR, handler); /* _psp is the starting address of the program in memory. The top of the stack is the end of the program. Using _SS and _SP together we can get the end of the stack. You may want to allow a bit of saftey space to insure that enough room is being allocated ie: (_SS + ((_SP + safety space)/16) - _psp) */ keep(0, (_SS + (_SP/16) - _psp)); return 0; } 函数名: kbhit 功 能: 检查当前按下的键 用 法: int kbhit(void); 程序例: #include int main(void) { cprintf("Press any key to continue:"); while (!kbhit()) /* do nothing */ ; cprintf("\r\nA key was pressed...\r\n"); return 0; } 函数名: keep 功 能: 退出并继续驻留 用 法: void keep(int status, int size); 程序例: /***NOTE: This is an interrupt service routine. You can NOT compile this program with Test Stack Overflow turned on and get an executable file which will operate correctly. Due to the nature of this function the formula used to compute the number of paragraphs may not necessarily work in all cases. Use with care! Terminate Stay Resident (TSR) programs are complex and no other support for them is provided. Refer to the MS-DOS technical documentation for more information. */ #include /* The clock tick interrupt */ #define INTR 0x1C /* Screen attribute (blue on grey) */ #define ATTR 0x7900 /* reduce heaplength and stacklength to make a smaller program in memory */ extern unsigned _heaplen = 1024; extern unsigned _stklen = 512; void interrupt ( *oldhandler)(void); void interrupt handler(void) { unsigned int (far *screen)[80]; static int count; /* For a color screen the video memory is at B800:0000. For a monochrome system use B000:000 */ screen = MK_FP(0xB800,0); /* increase the counter and keep it within 0 to 9 */ count++; count %= 10; /* put the number on the screen */ screen[0][79] = count + '0' + ATTR; /* call the old interrupt handler */ oldhandler(); } int main(void) { /* get the address of the current clock tick interrupt */ oldhandler = getvect(INTR); /* install the new interrupt handler */ setvect(INTR, handler); /* _psp is the starting address of the program in memory. The top of the stack is the end of the program. Using _SS and _SP together we can get the end of the stack. You may want to allow a bit of saftey space to insure that enough room is being allocated ie: (_SS + ((_SP + safety space)/16) - _psp) */ keep(0, (_SS + (_SP/16) - _psp)); return 0; } 函数大全(l开头) 函数名: labs 用 法: long labs(long n); 程序例: #include #include int main(void) { long result; long x = -12345678L; result= labs(x); printf("number: %ld abs value: %ld\n", x, result); return 0; } 函数名: ldexp 功 能: 计算value*2的幂 用 法: double ldexp(double value, int exp); 程序例: #include #include int main(void) { double value; double x = 2; /* ldexp raises 2 by a power of 3 then multiplies the result by 2 */ value = ldexp(x,3); printf("The ldexp value is: %lf\n", value); return 0; } 函数名: ldiv 功 能: 两个长整型数相除, 返回商和余数 用 法: ldiv_t ldiv(long lnumer, long ldenom); 程序例: /* ldiv example */ #include #include int main(void) { ldiv_t lx; lx = ldiv(100000L, 30000L); printf("100000 div 30000 = %ld remainder %ld\n", lx.quot, lx.rem); return 0; } 函数名: lfind 功 能: 执行线性搜索 用 法: void *lfind(void *key, void *base, int *nelem, int width, int (*fcmp)()); 程序例: #include #include int compare(int *x, int *y) { return( *x - *y ); } int main(void) { int array[5] = {35, 87, 46, 99, 12}; size_t nelem = 5; int key; int *result; key = 99; result = lfind(&key, array, &nelem, sizeof(int), (int(*)(const void *,const void *))compare); if (result) printf("Number %d found\n",key); else printf("Number %d not found\n",key); return 0; } 函数名: line 功 能: 在指定两点间画一直线 用 法: void far line(int x0, int y0, int x1, int y1); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int xmax, ymax; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); /* an error occurred */ if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } setcolor(getmaxcolor()); xmax = getmaxx(); ymax = getmaxy(); /* draw a diagonal line */ line(0, 0, xmax, ymax); /* clean up */ getch(); closegraph(); return 0; } 函数名: linerel 功 能: 从当前位置点(CP)到与CP有一给定相对距离的点画一直线 用 法: void far linerel(int dx, int dy); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); } /* move the C.P. to location (20, 30) */ moveto(20, 30); /* create and output a message at (20, 30) */ sprintf(msg, " (%d, %d)", getx(), gety()); outtextxy(20, 30, msg); /* draw a line to a point a relative distance away from the current value of C.P. */ linerel(100, 100); /* create and output a message at C.P. */ sprintf(msg, " (%d, %d)", getx(), gety()); outtext(msg); /* clean up */ getch(); closegraph(); return 0; } 函数名: localtime 功 能: 把日期和时间转变为结构 用 法: struct tm *localtime(long *clock); 程序例: #include #include #include int main(void) { time_t timer; struct tm *tblock; /* gets time of day */ timer = time(NULL); /* converts date/time to a structure */ tblock = localtime(&timer); printf("Local time is: %s", asctime(tblock)); return 0; } 函数名: lock 功 能: 设置文件共享锁 用 法: int lock(int handle, long offset, long length); 程序例: #include #include #include #include #include #include int main(void) { int handle, status; long length; /* Must have DOS Share.exe loaded for */ /* file locking to function properly */ handle = sopen("c:\\autoexec.bat", O_RDONLY,SH_DENYNO,S_IREAD); if (handle < 0) { printf("sopen failed\n"); exit(1); } length = filelength(handle); status = lock(handle,0L,length/2); if (status == 0) printf("lock succeeded\n"); else printf("lock failed\n"); status = unlock(handle,0L,length/2); if (status == 0) printf("unlock succeeded\n"); else printf("unlock failed\n"); close(handle); return 0; } 函数名: log 功 能: 对数函数ln(x) 用 法: double log(double x); 程序例: #include #include int main(void) { double result; double x = 8.6872; result = log(x); printf("The natural log of %lf is %lf\n", x, result); return 0; } 函数名: log10 功 能: 对数函数log 用 法: double log10(double x); 程序例: #include #include int main(void) { double result; double x = 800.6872; result = log10(x); printf("The common log of %lf is %lf\n", x, result); return 0; } 函数名: longjump 功 能: 执行非局部转移 用 法: void longjump(jmp_buf env, int val); 程序例: #include #include #include void subroutine(jmp_buf); int main(void) { int value; jmp_buf jumper; value = setjmp(jumper); if (value != 0) { printf("Longjmp with value %d\n", value); exit(value); } printf("About to call subroutine ... \n"); subroutine(jumper); return 0; } void subroutine(jmp_buf jumper) { longjmp(jumper,1); } 函数名: lowvideo 功 能: 选择低亮度字符 用 法: void lowvideo(void); 程序例: #include int main(void) { clrscr(); highvideo(); cprintf("High Intesity Text\r\n"); lowvideo(); gotoxy(1,2); cprintf("Low Intensity Text\r\n"); return 0; } 函数名: lrotl, _lrotl 功 能: 将无符号长整型数向左循环移位 用 法: unsigned long lrotl(unsigned long lvalue, int count); unsigned long _lrotl(unsigned long lvalue, int count); 程序例: /* lrotl example */ #include #include int main(void) { unsigned long result; unsigned long value = 100; result = _lrotl(value,1); printf("The value %lu rotated left one bit is: %lu\n", value, result); return 0; } 函数名: lsearch 功 能: 线性搜索 用 法: void *lsearch(const void *key, void *base, size_t *nelem, size_t width, int (*fcmp)(const void *, const void *)); 程序例: #include #include int compare(int *x, int *y) { return( *x - *y ); } int main(void) { int array[5] = {35, 87, 46, 99, 12}; size_t nelem = 5; int key; int *result; key = 99; result = lfind(&key, array, &nelem, sizeof(int), (int(*)(const void *,const void *))compare); if (result) printf("Number %d found\n",key); else printf("Number %d not found\n",key); return 0; } 函数名: lseek 功 能: 移动文件读/写指针 用 法: long lseek(int handle, long offset, int fromwhere); 程序例: #include #include #include #include #include int main(void) { int handle; char msg[] = "This is a test"; char ch; /* create a file */ handle = open("TEST.$$$", O_CREAT | O_RDWR, S_IREAD | S_IWRITE); /* write some data to the file */ write(handle, msg, strlen(msg)); /* seek to the begining of the file */ lseek(handle, 0L, SEEK_SET); /* reads chars from the file until we hit EOF */ do { read(handle, &ch, 1); printf("%c", ch); } while (!eof(handle)); close(handle); return 0; } v 函数大全(m开头) main()主函数 每一C 程序都 必须 有一main()函数, 可以根据自己的爱好把它放在程序的某 个地方。有些程序员把它放在最前面, 而另一些程序员把它放在最后面, 无论放 在哪个地方, 以下几点说明都是适合的。 1. main() 参数 在Turbo C2.0启动过程中, 传递main()函数三个参数: argc, argv和env。 * argc: 整数, 为传给main()的命令行参数个数。 * argv: 字符串数组。 在DOS 3.X 版本中, argv[0] 为程序运行的全路径名; 对DOS 3.0 以下的版本, argv[0]为空串("") 。 argv[1] 为在DOS命令行中执行程序名后的第一个字符串; argv[2] 为执行程序名后的第二个字符串; ... argv[argc]为NULL。 *env: 安符串数组。env[] 的每一个元素都包含ENVVAR=value形式的字符 串。其中ENVVAR为环境变量如PATH或87。value 为ENVVAR的对应值如C:\DOS, C: \TURBOC(对于PATH) 或YES(对于87)。 Turbo C2.0启动时总是把这三个参数传递给main()函数, 可以在用户程序中 说明(或不说明)它们, 如果说明了部分(或全部)参数, 它们就成为main()子程序 的局部变量。 请注意: 一旦想说明这些参数, 则必须按argc, argv, env 的顺序, 如以下 的例子: main() main(int argc) main(int argc, char *argv[]) main(int argc, char *argv[], char *env[]) 其中第二种情况是合法的, 但不常见, 因为在程序中很少有只用argc, 而不 用argv[]的情况。 以下提供一样例程序EXAMPLE.EXE, 演示如何在main()函数中使用三个参数: /*program name EXAMPLE.EXE*/ #include #include main(int argc, char *argv[], char *env[]) { int i; printf("These are the %d command- line arguments passed to main:\n\n", argc); for(i=0; i<=argc; i++) printf("argv[%d]:%s\n", i, argv[i]); printf("\nThe environment string(s)on this system are:\n\n"); for(i=0; env[i]!=NULL; i++) printf(" env[%d]:%s\n", i, env[i]); } 如果在DOS 提示符下, 按以下方式运行EXAMPLE.EXE: C:\example first_argument "argument with blanks" 3 4 "last but one" stop! 注意: 可以用双引号括起内含空格的参数, 如本例中的: " argument with blanks"和"Last but one")。 结果是这样的: The value of argc is 7 These are the 7 command-linearguments passed to main: argv[0]:C:\TURBO\EXAMPLE.EXE argv[1]:first_argument argv[2]:argument with blanks argv[3]:3 argv[4]:4 argv[5]:last but one argv[6]:stop! argv[7]:(NULL) The environment string(s) on this system are: env[0]: COMSPEC=C:\COMMAND.COM env[1]: PROMPT=$P$G /*视具体设置而定*/ env[2]: PATH=C:\DOS;C:\TC /*视具体设置而定*/ 应该提醒的是: 传送main() 函数的命令行参数的最大长度为128 个字符 (包 括参数间的空格), 这是由DOS 限制的。 函数名: matherr 功 能: 用户可修改的数学错误处理程序 用 法: int matherr(struct exception *e); 程序例: /* This is a user-defined matherr function that prevents any error messages from being printed. */ #include int matherr(struct exception *a) { return 1; } 函数名: memccpy 功 能: 从源source中拷贝n个字节到目标destin中 用 法: void *memccpy(void *destin, void *source, unsigned char ch, unsigned n); 程序例: #include #include int main(void) { char *src = "This is the source string"; char dest[50]; char *ptr; ptr = memccpy(dest, src, 'c', strlen(src)); if (ptr) { *ptr = '\0'; printf("The character was found: %s\n", dest); } else printf("The character wasn't found\n"); return 0; } 函数名: malloc 功 能: 内存分配函数 用 法: void *malloc(unsigned size); 程序例: #include #include #include #include int main(void) { char *str; /* allocate memory for string */ /* This will generate an error when compiling */ /* with C++, use the new operator instead. */ if ((str = malloc(10)) == NULL) { printf("Not enough memory to allocate buffer\n"); exit(1); /* terminate program if out of memory */ } /* copy "Hello" into string */ strcpy(str, "Hello"); /* display string */ printf("String is %s\n", str); /* free memory */ free(str); return 0; } 函数名: memchr 功 能: 在数组的前n个字节中搜索字符 用 法: void *memchr(void *s, char ch, unsigned n); 程序例: #include #include int main(void) { char str[17]; char *ptr; strcpy(str, "This is a string"); ptr = memchr(str, 'r', strlen(str)); if (ptr) printf("The character 'r' is at position: %d\n", ptr - str); else printf("The character was not found\n"); return 0; } 函数名: memcpy 功 能: 从源source中拷贝n个字节到目标destin中 用 法: void *memcpy(void *destin, void *source, unsigned n); 程序例: #include #include int main(void) { char src[] = "******************************"; char dest[] = "abcdefghijlkmnopqrstuvwxyz0123456709"; char *ptr; printf("destination before memcpy: %s\n", dest); ptr = memcpy(dest, src, strlen(src)); if (ptr) printf("destination after memcpy: %s\n", dest); else printf("memcpy failed\n"); return 0; } 函数名: memicmp 功 能: 比较两个串s1和s2的前n个字节, 忽略大小写 用 法: int memicmp(void *s1, void *s2, unsigned n); 程序例: #include #include int main(void) { char *buf1 = "ABCDE123"; char *buf2 = "abcde456"; int stat; stat = memicmp(buf1, buf2, 5); printf("The strings to position 5 are "); if (stat) printf("not "); printf("the same\n"); return 0; } 函数名: memmove 功 能: 移动一块字节 用 法: void *memmove(void *destin, void *source, unsigned n); 程序例: #include #include int main(void) { char *dest = "abcdefghijklmnopqrstuvwxyz0123456789"; char *src = "******************************"; printf("destination prior to memmove: %s\n", dest); memmove(dest, src, 26); printf("destination after memmove: %s\n", dest); return 0; } 函数名: memset 功 能: 设置s中的所有字节为ch, s数组的大小由n给定 用 法: void *memset(void *s, char ch, unsigned n); 程序例: #include #include #include int main(void) { char buffer[] = "Hello world\n"; printf("Buffer before memset: %s\n", buffer); memset(buffer, '*', strlen(buffer) - 1); printf("Buffer after memset: %s\n", buffer); return 0; } 函数名: mkdir 功 能: 建立一个目录 用 法: int mkdir(char *pathname); 程序例: #include #include #include #include int main(void) { int status; clrscr(); status = mkdir("asdfjklm"); (!status) ? (printf("Directory created\n")) : (printf("Unable to create directory\n")); getch(); system("dir"); getch(); status = rmdir("asdfjklm"); (!status) ? (printf("Directory deleted\n")) : (perror("Unable to delete directory")); return 0; } 函数名: mktemp 功 能: 建立唯一的文件名 用 法: char *mktemp(char *template); 程序例: #include #include int main(void) { /* fname defines the template for the temporary file. */ char *fname = "TXXXXXX", *ptr; ptr = mktemp(fname); printf("%s\n",ptr); return 0; } 函数名: MK_FP 功 能: 设置一个远指针 用 法: void far *MK_FP(unsigned seg, unsigned off); 程序例: #include #include int main(void) { int gd, gm, i; unsigned int far *screen; detectgraph(&gd, &gm); if (gd == HERCMONO) screen = MK_FP(0xB000, 0); else screen = MK_FP(0xB800, 0); for (i=0; i<26; i++) screen[i] = 0x0700 + ('a' + i); return 0; } 函数名: modf 功 能: 把数分为指数和尾数 用 法: double modf(double value, double *iptr); 程序例: #include #include int main(void) { double fraction, integer; double number = 100000.567; fraction = modf(number, &integer); printf("The whole and fractional parts of %lf are %lf and %lf\n", number, integer, fraction); return 0; } 函数名: movedata 功 能: 拷贝字节 用 法: void movedata(int segsrc, int offsrc, int segdest, int offdest, unsigned numbytes); 程序例: #include #define MONO_BASE 0xB000 /* saves the contents of the monochrome screen in buffer */ void save_mono_screen(char near *buffer) { movedata(MONO_BASE, 0, _DS, (unsigned)buffer, 80*25*2); } int main(void) { char buf[80*25*2]; save_mono_screen(buf); } 函数名: moverel 功 能: 将当前位置(CP)移动一相对距离 用 法: void far moverel(int dx, int dy); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move the C.P. to location (20, 30) */ moveto(20, 30); /* plot a pixel at the C.P. */ putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at (20, 30) */ sprintf(msg, " (%d, %d)", getx(), gety()); outtextxy(20, 30, msg); /* move to a point a relative distance */ /* away from the current value of C.P. */ moverel(100, 100); /* plot a pixel at the C.P. */ putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at C.P. */ sprintf(msg, " (%d, %d)", getx(), gety()); outtext(msg); /* clean up */ getch(); closegraph(); return 0; } 函数名: movetext 功 能: 将屏幕文本从一个矩形区域拷贝到另一个矩形区域 用 法: int movetext(int left, int top, int right, int bottom, int newleft, int newtop); 程序例: #include #include int main(void) { char *str = "This is a test string"; clrscr(); cputs(str); getch(); movetext(1, 1, strlen(str), 2, 10, 10); getch(); return 0; } 函数名: moveto 功 能: 将CP移到(x, y) 用 法: void far moveto(int x, int y); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move the C.P. to location (20, 30) */ moveto(20, 30); /* plot a pixel at the C.P. */ putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at (20, 30) */ sprintf(msg, " (%d, %d)", getx(), gety()); outtextxy(20, 30, msg); /* move to (100, 100) */ moveto(100, 100); /* plot a pixel at the C.P. */ putpixel(getx(), gety(), getmaxcolor()); /* create and output a message at C.P. */ sprintf(msg, " (%d, %d)", getx(), gety()); outtext(msg); /* clean up */ getch(); closegraph(); return 0; } 函数名: movemem 功 能: 移动一块字节 用 法: void movemem(void *source, void *destin, unsigned len); 程序例: #include #include #include #include int main(void) { char *source = "Borland International"; char *destination; int length; length = strlen(source); destination = malloc(length + 1); movmem(source,destination,length); printf("%s\n",destination); return 0; } 函数名: normvideo 功 能: 选择正常亮度字符 用 法: void normvideo(void); 程序例: #include int main(void) { normvideo(); cprintf("NORMAL Intensity Text\r\n"); return 0; } 函数名: nosound 功 能: 关闭PC扬声器 用 法: void nosound(void); 程序例: /* Emits a 7-Hz tone for 10 seconds. True story: 7 Hz is the resonant frequency of a chicken's skull cavity. This was determined empirically in Australia, where a new factory generating 7-Hz tones was located too close to a chicken ranch: When the factory started up, all the chickens died. Your PC may not be able to emit a 7-Hz tone. */ int main(void) { sound(7); delay(10000); nosound(); } 函数大全(n ,o开头) void normvideo(void ); 选择正常亮度字符。 将文本属性(前景和背景)置为启动程序时它所具有的值,来选择标准字符。 void nosound(void ); 关闭由调用 sound而发声的扬声器。 函数名: open 功 能: 打开一个文件用于读或写 用 法: int open(char *pathname, int access[, int permiss]); 程序例: #include #include #include #include int main(void) { int handle; char msg[] = "Hello world"; if ((handle = open("TEST.$$$", O_CREAT | O_TEXT)) == -1) { perror("Error:"); return 1; } write(handle, msg, strlen(msg)); close(handle); return 0; } 函数名: outport 功 能: 输出整数到硬件端口中 用 法: void outport(int port, int value); 程序例: #include #include int main(void) { int value = 64; int port = 0; outportb(port, value); printf("Value %d sent to port number %d\n", value, port); return 0; } 函数名: outportb 功 能: 输出字节到硬件端口中 用 法: void outportb(int port, char byte); 程序例: #include #include int main(void) { int value = 64; int port = 0; outportb(port, value); printf("Value %d sent to port number %d\n", value, port); return 0; } 函数名: outtext 功 能: 在视区显示一个字符串 用 法: void far outtext(char far *textstring); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* move the C.P. to the center of the screen */ moveto(midx, midy); /* output text starting at the C.P. */ outtext("This "); outtext("is "); outtext("a "); outtext("test."); /* clean up */ getch(); closegraph(); return 0; } 函数名: outtextxy 功 能: 在指定位置显示一字符串 用 法: void far outtextxy(int x, int y, char *textstring); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; /* initialize graphics and local variables */ initgraph( &gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* output text at the center of the screen*/ /* Note: the C.P. doesn't get changed.*/ outtextxy(midx, midy, "This is a test."); /* clean up */ getch(); closegraph(); return 0; } 函数大全(p开头) 函数名: parsfnm 功 能: 分析文件名 用 法: char *parsfnm (char *cmdline, struct fcb *fcbptr, int option); 程序例: #include #include #include #include int main(void) { char line[80]; struct fcb blk; /* get file name */ printf("Enter drive and file name (no path - ie. a:file.dat)\n"); gets(line); /* put file name in fcb */ if (parsfnm(line, &blk, 1) == NULL) printf("Error in parsfm call\n"); else printf("Drive #%d Name: %11s\n", blk.fcb_drive, blk.fcb_name); return 0; } 函数名: peek 功 能: 检查存储单元 用 法: int peek(int segment, unsigned offset); 程序例: #include #include #include int main(void) { int value = 0; printf("The current status of your keyboard is:\n"); value = peek(0x0040, 0x0017); if (value & 1) printf("Right shift on\n"); else printf("Right shift off\n"); if (value & 2) printf("Left shift on\n"); else printf("Left shift off\n"); if (value & 4) printf("Control key on\n"); else printf("Control key off\n"); if (value & 8) printf("Alt key on\n"); else printf("Alt key off\n"); if (value & 16) printf("Scroll lock on\n"); else printf("Scroll lock off\n"); if (value & 32) printf("Num lock on\n"); else printf("Num lock off\n"); if (value & 64) printf("Caps lock on\n"); else printf("Caps lock off\n"); return 0; } 函数名: peekb 功 能: 检查存储单元 用 法: char peekb (int segment, unsigned offset); 程序例: #include #include #include int main(void) { int value = 0; printf("The current status of your keyboard is:\n"); value = peekb(0x0040, 0x0017); if (value & 1) printf("Right shift on\n"); else printf("Right shift off\n"); if (value & 2) printf("Left shift on\n"); else printf("Left shift off\n"); if (value & 4) printf("Control key on\n"); else printf("Control key off\n"); if (value & 8) printf("Alt key on\n"); else printf("Alt key off\n"); if (value & 16) printf("Scroll lock on\n"); else printf("Scroll lock off\n"); if (value & 32) printf("Num lock on\n"); else printf("Num lock off\n"); if (value & 64) printf("Caps lock on\n"); else printf("Caps lock off\n"); return 0; } 函数名: perror 功 能: 系统错误信息 用 法: void perror(char *string); 程序例: #include int main(void) { FILE *fp; fp = fopen("perror.dat", "r"); if (!fp) perror("Unable to open file for reading"); return 0; } 函数名: pieslice 功 能: 绘制并填充一个扇形 用 法: void far pieslice(int x, int stanle, int endangle, int radius); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int stangle = 45, endangle = 135, radius = 100; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* set fill style and draw a pie slice */ setfillstyle(EMPTY_FILL, getmaxcolor()); pieslice(midx, midy, stangle, endangle, radius); /* clean up */ getch(); closegraph(); return 0; } 函数名: poke 功 能: 存值到一个给定存储单元 用 法: void poke(int segment, int offset, int value); 程序例: #include #include int main(void) { clrscr(); cprintf("Make sure the scroll lock key is off and press any key\r\n"); getch(); poke(0x0000,0x0417,16); cprintf("The scroll lock is now on\r\n"); return 0; } 函数名: pokeb 功 能: 存值到一个给定存储单元 用 法: void pokeb(int segment, int offset, char value); 程序例: #include #include int main(void) { clrscr(); cprintf("Make sure the scroll lock key is off and press any key\r\n"); getch(); pokeb(0x0000,0x0417,16); cprintf("The scroll lock is now on\r\n"); return 0; } 函数名: poly 功 能: 根据参数产生一个多项式 用 法: double poly(double x, int n, double c[]); 程序例: #include #include /* polynomial: x**3 - 2x**2 + 5x - 1 */ int main(void) { double array[] = { -1.0, 5.0, -2.0, 1.0 }; double result; result = poly(2.0, 3, array); printf("The polynomial: x**3 - 2.0x**2 + 5x - 1 at 2.0 is %lf\n", result); return 0; } 函数名: pow 功 能: 指数函数(x的y次方) 用 法: double pow(double x, double y); 程序例: #include #include int main(void) { double x = 2.0, y = 3.0; printf("%lf raised to %lf is %lf\n", x, y, pow(x, y)); return 0; } 函数名: pow10 功 能: 指数函数(10的p次方) 用 法: double pow10(int p); 程序例: #include #include int main(void) { double p = 3.0; printf("Ten raised to %lf is %lf\n", p, pow10(p)); return 0; } 函数名: printf 功 能: 产生格式化输出的函数 用 法: int printf(char *format...); 程序例: #include #include #define I 555 #define R 5.5 int main(void) { int i,j,k,l; char buf[7]; char *prefix = buf; char tp[20]; printf("prefix 6d 6o 8x 10.2e " "10.2f\n"); strcpy(prefix,"%"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) for (l = 0; l < 2; l++) { if (i==0) strcat(prefix,"-"); if (j==0) strcat(prefix,"+"); if (k==0) strcat(prefix,"#"); if (l==0) strcat(prefix,"0"); printf("%5s |",prefix); strcpy(tp,prefix); strcat(tp,"6d |"); printf(tp,I); strcpy(tp,""); strcpy(tp,prefix); strcat(tp,"6o |"); printf(tp,I); strcpy(tp,""); strcpy(tp,prefix); strcat(tp,"8x |"); printf(tp,I); strcpy(tp,""); strcpy(tp,prefix); strcat(tp,"10.2e |"); printf(tp,R); strcpy(tp,prefix); strcat(tp,"10.2f |"); printf(tp,R); printf(" \n"); strcpy(prefix,"%"); } } return 0; } 函数名: putc 功 能: 输出一字符到指定流中 用 法: int putc(int ch, FILE *stream); 程序例: #include int main(void) { char msg[] = "Hello world\n"; int i = 0; while (msg[i]) putc(msg[i++], stdout); return 0; } 函数名: putch 功 能: 输出字符到控制台 用 法: int putch(int ch); 程序例: #include #include int main(void) { char ch = 0; printf("Input a string:"); while ((ch != '\r')) { ch = getch(); putch(ch); } return 0; } 函数名: putchar 功 能: 在stdout上输出字符 用 法: int putchar(int ch); 程序例: #include /* define some box-drawing characters */ #define LEFT_TOP 0xDA #define RIGHT_TOP 0xBF #define HORIZ 0xC4 #define VERT 0xB3 #define LEFT_BOT 0xC0 #define RIGHT_BOT 0xD9 int main(void) { char i, j; /* draw the top of the box */ putchar(LEFT_TOP); for (i=0; i<10; i++) putchar(HORIZ); putchar(RIGHT_TOP); putchar('\n'); /* draw the middle */ for (i=0; i<4; i++) { putchar(VERT); for (j=0; j<10; j++) putchar(' '); putchar(VERT); putchar('\n'); } /* draw the bottom */ putchar(LEFT_BOT); for (i=0; i<10; i++) putchar(HORIZ); putchar(RIGHT_BOT); putchar('\n'); return 0; } 函数名: putenv 功 能: 把字符串加到当前环境中 用 法: int putenv(char *envvar); 程序例: #include #include #include #include #include int main(void) { char *path, *ptr; int i = 0; /* get the current path environment */ ptr = getenv("PATH"); /* set up new path */ path = malloc(strlen(ptr)+15); strcpy(path,"PATH="); strcat(path,ptr); strcat(path,";c:\\temp"); /* replace the current path and display current environment */ putenv(path); while (environ[i]) printf("%s\n",environ[i++]); return 0; } 函数名: putimage 功 能: 在屏幕上输出一个位图 用 法: void far putimage(int x, int y, void far *bitmap, int op); 程序例: #include #include #include #include #define ARROW_SIZE 10 void draw_arrow(int x, int y); int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; void *arrow; int x, y, maxx; unsigned int size; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); x = 0; y = getmaxy() / 2; /* draw the image to be grabbed */ draw_arrow(x, y); /* calculate the size of the image */ size = imagesize(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE); /* allocate memory to hold the image */ arrow = malloc(size); /* grab the image */ getimage(x, y-ARROW_SIZE, x+(4*ARROW_SIZE), y+ARROW_SIZE, arrow); /* repeat until a key is pressed */ while (!kbhit()) { /* erase old image */ putimage(x, y-ARROW_SIZE, arrow, XOR_PUT); x += ARROW_SIZE; if (x >= maxx) x = 0; /* plot new image */ putimage(x, y-ARROW_SIZE, arrow, XOR_PUT); } /* clean up */ free(arrow); closegraph(); return 0; } void draw_arrow(int x, int y) { /* draw an arrow on the screen */ moveto(x, y); linerel(4*ARROW_SIZE, 0); linerel(-2*ARROW_SIZE, -1*ARROW_SIZE); linerel(0, 2*ARROW_SIZE); linerel(2*ARROW_SIZE, -1*ARROW_SIZE); } 函数名: putpixel 功 能: 在指定位置画一像素 用 法: void far putpixel (int x, int y, int pixelcolor); 程序例: #include #include #include #include #include #define PIXEL_COUNT 1000 #define DELAY_TIME 100 /* in milliseconds */ int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int i, x, y, color, maxx, maxy, maxcolor, seed; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx() + 1; maxy = getmaxy() + 1; maxcolor = getmaxcolor() + 1; while (!kbhit()) { /* seed the random number generator */ seed = random(32767); srand(seed); for (i=0; i { x = random(maxx); y = random(maxy); color = random(maxcolor); putpixel(x, y, color); } delay(DELAY_TIME); srand(seed); for (i=0; i { x = random(maxx); y = random(maxy); color = random(maxcolor); if (color == getpixel(x, y)) putpixel(x, y, 0); } } /* clean up */ getch(); closegraph(); return 0; } 函数名: puts 功 能: 送一字符串到流中 用 法: int puts(char *string); 程序例: #include int main(void) { char string[] = "This is an example output string\n"; puts(string); return 0; } 函数名: puttext 功 能: 将文本从存储区拷贝到屏幕 用 法: int puttext(int left, int top, int right, int bottom, void *source); 程序例: #include int main(void) { char buffer[512]; /* put some text to the console */ clrscr(); gotoxy(20, 12); cprintf("This is a test. Press any key to continue ..."); getch(); /* grab screen contents */ gettext(20, 12, 36, 21,buffer); clrscr(); /* put selected characters back to the screen */ gotoxy(20, 12); puttext(20, 12, 36, 21, buffer); getch(); return 0; } 函数名: putw 功 能: 把一字符或字送到流中 用 法: int putw(int w, FILE *stream); 程序例: #include #include #define FNAME "test.$$$" int main(void) { FILE *fp; int word; /* place the word in a file */ fp = fopen(FNAME, "wb"); if (fp == NULL) { printf("Error opening file %s\n", FNAME); exit(1); } word = 94; putw(word,fp); if (ferror(fp)) printf("Error writing to file\n"); else printf("Successful write\n"); fclose(fp); /* reopen the file */ fp = fopen(FNAME, "rb"); if (fp == NULL) { printf("Error opening file %s\n", FNAME); exit(1); } /* extract the word */ word = getw(fp); if (ferror(fp)) printf("Error reading file\n"); else printf("Successful read: word = %d\n", word); /* clean up */ fclose(fp); unlink(FNAME); return 0; } 函数大全(q,r开头) 函数名: qsort 功 能: 使用快速排序例程进行排序 用 法: void qsort(void *base, int nelem, int width, int (*fcmp)()); 程序例: #include #include #include int sort_function( const void *a, const void *b); char list[5][4] = { "cat", "car", "cab", "cap", "can" }; int main(void) { int x; qsort((void *)list, 5, sizeof(list[0]), sort_function); for (x = 0; x < 5; x++) printf("%s\n", list[x]); return 0; } int sort_function( const void *a, const void *b) { return( strcmp(a,b) ); } 函数名: qsort 功 能: 使用快速排序例程进行排序 用 法: void qsort(void *base, int nelem, int width, int (*fcmp)()); 程序例: #include #include #include int sort_function( const void *a, const void *b); char list[5][4] = { "cat", "car", "cab", "cap", "can" }; int main(void) { int x; qsort((void *)list, 5, sizeof(list[0]), sort_function); for (x = 0; x < 5; x++) printf("%s\n", list[x]); return 0; } int sort_function( const void *a, const void *b) { return( strcmp(a,b) ); } 函数名: raise 功 能: 向正在执行的程序发送一个信号 用 法: int raise(int sig); 程序例: #include int main(void) { int a, b; a = 10; b = 0; if (b == 0) /* preempt divide by zero error */ raise(SIGFPE); a = a / b; return 0; } 函数名: rand 功 能: 随机数发生器 用 法: void rand(void); 程序例: #include #include int main(void) { int i; printf("Ten random numbers from 0 to 99\n\n"); for(i=0; i<10; i++) printf("%d\n", rand() % 100); return 0; } 函数名: randbrd 功 能: 随机块读 用 法: int randbrd(struct fcb *fcbptr, int reccnt); 程序例: #include #include #include #include int main(void) { char far *save_dta; char line[80], buffer[256]; struct fcb blk; int i, result; /* get user input file name for dta */ printf("Enter drive and file name (no path - i.e. a:file.dat)\n"); gets(line); /* put file name in fcb */ if (!parsfnm(line, &blk, 1)) { printf("Error in call to parsfnm\n"); exit(1); } printf("Drive #%d File: %s\n\n", blk.fcb_drive, blk.fcb_name); /* open file with DOS FCB open file */ bdosptr(0x0F, &blk, 0); /* save old dta, and set new one */ save_dta = getdta(); setdta(buffer); /* set up info for the new dta */ blk.fcb_recsize = 128; blk.fcb_random = 0L; result = randbrd(&blk, 1); /* check results from randbrd */ if (!result) printf("Read OK\n\n"); else { perror("Error during read"); exit(1); } /* read in data from the new dta */ printf("The first 128 characters are:\n"); for (i=0; i<128; i++) putchar(buffer[i]); /* restore previous dta */ setdta(save_dta); return 0; } 函数名: randbwr 功 能: 随机块写 用 法: int randbwr(struct fcp *fcbptr, int reccnt); 程序例: #include #include #include #include int main(void) { char far *save_dta; char line[80]; char buffer[256] = "RANDBWR test!"; struct fcb blk; int result; /* get new file name from user */ printf("Enter a file name to create (no path - ie. a:file.dat\n"); gets(line); /* parse the new file name to the dta */ parsfnm(line,&blk,1); printf("Drive #%d File: %s\n", blk.fcb_drive, blk.fcb_name); /* request DOS services to create file */ if (bdosptr(0x16, &blk, 0) == -1) { perror("Error creating file"); exit(1); } /* save old dta and set new dta */ save_dta = getdta(); setdta(buffer); /* write new records */ blk.fcb_recsize = 256; blk.fcb_random = 0L; result = randbwr(&blk, 1); if (!result) printf("Write OK\n"); else { perror("Disk error"); exit(1); } /* request DOS services to close the file */ if (bdosptr(0x10, &blk, 0) == -1) { perror("Error closing file"); exit(1); } /* reset the old dta */ setdta(save_dta); return 0; } 函数名: random 功 能: 随机数发生器 用 法: int random(int num); 程序例: #include #include #include /* prints a random number in the range 0 to 99 */ int main(void) { randomize(); printf("Random number in the 0-99 range: %d\n", random (100)); return 0; } 函数名: randomize 功 能: 初始化随机数发生器 用 法: void randomize(void); 程序例: #include #include #include int main(void) { int i; randomize(); printf("Ten random numbers from 0 to 99\n\n"); for(i=0; i<10; i++) printf("%d\n", rand() % 100); return 0; } 函数名: read 功 能: 从文件中读 用 法: int read(int handle, void *buf, int nbyte); 程序例: #include #include #include #include #include #include int main(void) { void *buf; int handle, bytes; buf = malloc(10); /* Looks for a file in the current directory named TEST.$$$ and attempts to read 10 bytes from it. To use this example you should create the file TEST.$$$ */ if ((handle = open("TEST.$$$", O_RDONLY | O_BINARY, S_IWRITE | S_IREAD)) == -1) { printf("Error Opening File\n"); exit(1); } if ((bytes = read(handle, buf, 10)) == -1) { printf("Read Failed.\n"); exit(1); } else { printf("Read: %d bytes read.\n", bytes); } return 0; } 函数名: realloc 功 能: 重新分配主存 用 法: void *realloc(void *ptr, unsigned newsize); 程序例: #include #include #include int main(void) { char *str; /* allocate memory for string */ str = malloc(10); /* copy "Hello" into string */ strcpy(str, "Hello"); printf("String is %s\n Address is %p\n", str, str); str = realloc(str, 20); printf("String is %s\n New address is %p\n", str, str); /* free memory */ free(str); return 0; } 函数名: rectangle 功 能: 画一个矩形 用 法: void far rectangle(int left, int top, int right, int bottom); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int left, top, right, bottom; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } left = getmaxx() / 2 - 50; top = getmaxy() / 2 - 50; right = getmaxx() / 2 + 50; bottom = getmaxy() / 2 + 50; /* draw a rectangle */ rectangle(left,top,right,bottom); /* clean up */ getch(); closegraph(); return 0; } 函数名: registerbgidriver 功 能: 登录已连接进来的图形驱动程序代码 用 法: int registerbgidriver(void(*driver)(void)); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* register a driver that was added into graphics.lib */ errorcode = registerbgidriver(EGAVGA_driver); /* report any registration errors */ if (errorcode < 0) { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } 函数名: remove 功 能: 删除一个文件 用 法: int remove(char *filename); 程序例: #include int main(void) { char file[80]; /* prompt for file name to delete */ printf("File to delete: "); gets(file); /* delete the file */ if (remove(file) == 0) printf("Removed %s.\n",file); else perror("remove"); return 0; } 函数名: rename 功 能: 重命名文件 用 法: int rename(char *oldname, char *newname); 程序例: #include int main(void) { char oldname[80], newname[80]; /* prompt for file to rename and new name */ printf("File to rename: "); gets(oldname); printf("New name: "); gets(newname); /* Rename the file */ if (rename(oldname, newname) == 0) printf("Renamed %s to %s.\n", oldname, newname); else perror("rename"); return 0; } 函数名: restorecrtmode 功 能: 将屏幕模式恢复为先前的imitgraph设置 用 法: void far restorecrtmode(void); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int x, y; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "Press any key to exit graphics:"); getch(); /* restore system to text mode */ restorecrtmode(); printf("We're now in text mode.\n"); printf("Press any key to return to graphics mode:"); getch(); /* return to graphics mode */ setgraphmode(getgraphmode()); /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "We're back in graphics mode."); outtextxy(x, y+textheight("W"), "Press any key to halt:"); /* clean up */ getch(); closegraph(); return 0; } 函数名: rewind 功 能: 将文件指针重新指向一个流的开头 用 法: int rewind(FILE *stream); 程序例: #include #include int main(void) { FILE *fp; char *fname = "TXXXXXX", *newname, first; newname = mktemp(fname); fp = fopen(newname,"w+"); fprintf(fp,"abcdefghijklmnopqrstuvwxyz"); rewind(fp); fscanf(fp,"%c",&first); printf("The first character is: %c\n",first); fclose(fp); remove(newname); return 0; } 函数名: rmdir 功 能: 删除DOS文件目录 用 法: int rmdir(char *stream); 程序例: #include #include #include #include #define DIRNAME "testdir.$$$" int main(void) { int stat; stat = mkdir(DIRNAME); if (!stat) printf("Directory created\n"); else { printf("Unable to create directory\n"); exit(1); } getch(); system("dir/p"); getch(); stat = rmdir(DIRNAME); if (!stat) printf("\nDirectory deleted\n"); else { perror("\nUnable to delete directory\n"); exit(1); } return 0; } 函数大全(s开头) 函数名: sbrk 功 能: 改变数据段空间位置 用 法: char *sbrk(int incr); 程序例: #include #include int main(void) { printf("Changing allocation with sbrk()\n"); printf("Before sbrk() call: %lu bytes free\n", (unsigned long) coreleft()); sbrk(1000); printf(" After sbrk() call: %lu bytes free\n", (unsigned long) coreleft()); return 0; } 函数名: scanf 功 能: 执行格式化输入 用 法: int scanf(char *format[,argument,...]); 程序例: #include #include int main(void) { char label[20]; char name[20]; int entries = 0; int loop, age; double salary; struct Entry_struct { char name[20]; int age; float salary; } entry[20]; /* Input a label as a string of characters restricting to 20 characters */ printf("\n\nPlease enter a label for the chart: "); scanf("%20s", label); fflush(stdin); /* flush the input stream in case of bad input */ /* Input number of entries as an integer */ printf("How many entries will there be? (less than 20) "); scanf("%d", &entries); fflush(stdin); /* flush the input stream in case of bad input */ /* input a name restricting input to only letters upper or lower case */ for (loop=0;loop { printf("Entry %d\n", loop); printf(" Name : "); scanf("%[A-Za-z]", entry[loop].name); fflush(stdin); /* flush the input stream in case of bad input */ /* input an age as an integer */ printf(" Age : "); scanf("%d", &entry[loop].age); fflush(stdin); /* flush the input stream in case of bad input */ /* input a salary as a float */ printf(" Salary : "); scanf("%f", &entry[loop].salary); fflush(stdin); /* flush the input stream in case of bad input */ } /* Input a name, age and salary as a string, integer, and double */ printf("\nPlease enter your name, age and salary\n"); scanf("%20s %d %lf", name, &age, &salary); /* Print out the data that was input */ printf("\n\nTable %s\n",label); printf("Compiled by %s age %d $%15.2lf\n", name, age, salary); printf("-----------------------------------------------------\n"); for (loop=0;loop printf("%4d | %-20s | %5d | %15.2lf\n", loop + 1, entry[loop].name, entry[loop].age, entry[loop].salary); printf("-----------------------------------------------------\n"); return 0; } 函数名: searchpath 功 能: 搜索DOS路径 用 法: char *searchpath(char *filename); 程序例: #include #include int main(void) { char *p; /* Looks for TLINK and returns a pointer to the path */ p = searchpath("TLINK.EXE"); printf("Search for TLINK.EXE : %s\n", p); /* Looks for non-existent file */ p = searchpath("NOTEXIST.FIL"); printf("Search for NOTEXIST.FIL : %s\n", p); return 0; } 函数名: sector 功 能: 画并填充椭圆扇区 用 法: void far sector(int x, int y, int stangle, int endangle); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, i; int stangle = 45, endangle = 135; int xrad = 100, yrad = 50; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through the fill patterns */ for (i=EMPTY_FILL; i { /* set the fill style */ setfillstyle(i, getmaxcolor()); /* draw the sector slice */ sector(midx, midy, stangle, endangle, xrad, yrad); getch(); } /* clean up */ closegraph(); return 0; } 函数名: segread 功 能: 读段寄存器值 用 法: void segread(struct SREGS *segtbl); 程序例: #include #include int main(void) { struct SREGS segs; segread(&segs); printf("Current segment register settings\n\n"); printf("CS: %X DS: %X\n", segs.cs, segs.ds); printf("ES: %X SS: %X\n", segs.es, segs.ss); return 0; } 函数名: setactivepage 功 能: 设置图形输出活动页 用 法: void far setactivepage(int pagenum); 程序例: #include #include #include #include int main(void) { /* select a driver and mode that supports */ /* multiple pages. */ int gdriver = EGA, gmode = EGAHI, errorcode; int x, y, ht; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; ht = textheight("W"); /* select the off screen page for drawing */ setactivepage(1); /* draw a line on page #1 */ line(0, 0, getmaxx(), getmaxy()); /* output a message on page #1 */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "This is page #1:"); outtextxy(x, y+ht, "Press any key to halt:"); /* select drawing to page #0 */ setactivepage(0); /* output a message on page #0 */ outtextxy(x, y, "This is page #0."); outtextxy(x, y+ht, "Press any key to view page #1:"); getch(); /* select page #1 as the visible page */ setvisualpage(1); /* clean up */ getch(); closegraph(); return 0; } 函数名: setallpallette 功 能: 按指定方式改变所有的调色板颜色 用 法: void far setallpallette(struct palette, far *pallette); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; struct palettetype pal; int color, maxcolor, ht; int y = 10; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxcolor = getmaxcolor(); ht = 2 * textheight("W"); /* grab a copy of the palette */ getpalette(&pal); /* display the default palette colors */ for (color=1; color<=maxcolor; color++) { setcolor(color); sprintf(msg, "Color: %d", color); outtextxy(1, y, msg); y += ht; } /* wait for a key */ getch(); /* black out the colors one by one */ for (color=1; color<=maxcolor; color++) { setpalette(color, BLACK); getch(); } /* restore the palette colors */ setallpalette(&pal); /* clean up */ getch(); closegraph(); return 0; } 函数名: setaspectratio 功 能: 设置图形纵横比 用 法: void far setaspectratio(int xasp, int yasp); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int xasp, yasp, midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* get current aspect ratio settings */ getaspectratio(&xasp, &yasp); /* draw normal circle */ circle(midx, midy, 100); getch(); /* claer the screen */ cleardevice(); /* adjust the aspect for a wide circle */ setaspectratio(xasp/2, yasp); circle(midx, midy, 100); getch(); /* adjust the aspect for a narrow circle */ cleardevice(); setaspectratio(xasp, yasp/2); circle(midx, midy, 100); /* clean up */ getch(); closegraph(); return 0; } 函数名: setbkcolor 功 能: 用调色板设置当前背景颜色 用 法: void far setbkcolor(int color); 程序例: #include #include #include #include int main(void) { /* select a driver and mode that supports */ /* multiple background colors. */ int gdriver = EGA, gmode = EGAHI, errorcode; int bkcol, maxcolor, x, y; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (bkcol=0; bkcol<=maxcolor; bkcol++) { /* clear the screen */ cleardevice(); /* select a new background color */ setbkcolor(bkcol); /* output a messsage */ if (bkcol == WHITE) setcolor(EGA_BLUE); sprintf(msg, "Background color: %d", bkcol); outtextxy(x, y, msg); getch(); } /* clean up */ closegraph(); return 0; } 函数名: setblock 功 能: 修改先前已分配的DOS存储段大小 用 法: int setblock(int seg, int newsize); 程序例: #include #include #include #include int main(void) { unsigned int size, segp; int stat; size = 64; /* (64 x 16) = 1024 bytes */ stat = allocmem(size, &segp); if (stat == -1) printf("Allocated memory at segment: %X\n", segp); else { printf("Failed: maximum number of paragraphs available is %d\n", stat); exit(1); } stat = setblock(segp, size * 2); if (stat == -1) printf("Expanded memory block at segment: %X\n", segp); else printf("Failed: maximum number of paragraphs available is %d\n", stat); freemem(segp); return 0; } 函数名: setbuf 功 能: 把缓冲区与流相联 用 法: void setbuf(FILE *steam, char *buf); 程序例: #include /* BUFSIZ is defined in stdio.h */ char outbuf[BUFSIZ]; int main(void) { /* attach a buffer to the standard output stream */ setbuf(stdout, outbuf); /* put some characters into the buffer */ puts("This is a test of buffered output.\n\n"); puts("This output will go into outbuf\n"); puts("and won't appear until the buffer\n"); puts("fills up or we flush the stream.\n"); /* flush the output buffer */ fflush(stdout); return 0; } 函数名: setcbrk 功 能: 设置Control-break 用 法: int setcbrk(int value); 程序例: #include #include #include int main(void) { int break_flag; printf("Enter 0 to turn control break off\n"); printf("Enter 1 to turn control break on\n"); break_flag = getch() - 0; setcbrk(break_flag); if (getcbrk()) printf("Cntrl-brk flag is on\n"); else printf("Cntrl-brk flag is off\n"); return 0; } 函数名: setcolor 功 能: 设置当前画线颜色 用 法: void far setcolor(int color); 程序例: #include #include #include #include int main(void) { /* select a driver and mode that supports */ /* multiple drawing colors. */ int gdriver = EGA, gmode = EGAHI, errorcode; int color, maxcolor, x, y; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (color=1; color<=maxcolor; color++) { /* clear the screen */ cleardevice(); /* select a new background color */ setcolor(color); /* output a messsage */ sprintf(msg, "Color: %d", color); outtextxy(x, y, msg); getch(); } /* clean up */ closegraph(); return 0; } 函数名: setdate 功 能: 设置DOS日期 用 法: void setdate(struct date *dateblk); 程序例: #include #include #include int main(void) { struct date reset; struct date save_date; getdate(&save_date); printf("Original date:\n"); system("date"); reset.da_year = 2001; reset.da_day = 1; reset.da_mon = 1; setdate(&reset); printf("Date after setting:\n"); system("date"); setdate(&save_date); printf("Back to original date:\n"); system("date"); return 0; } 函数名: setdisk 功 能: 设置当前磁盘驱动器 用 法: int setdisk(int drive); 程序例: #include #include int main(void) { int save, disk, disks; /* save original drive */ save = getdisk(); /* print number of logic drives */ disks = setdisk(save); printf("%d logical drives on the system\n\n", disks); /* print the drive letters available */ printf("Available drives:\n"); for (disk = 0;disk < 26;++disk) { setdisk(disk); if (disk == getdisk()) printf("%c: drive is available\n", disk + 'a'); } setdisk(save); return 0; } 函数名: setdta 功 能: 设置磁盘传输区地址 用 法: void setdta(char far *dta); 程序例: #include #include #include #include int main(void) { char line[80], far *save_dta; char buffer[256] = "SETDTA test!"; struct fcb blk; int result; /* get new file name from user */ printf("Enter a file name to create:"); gets(line); /* parse the new file name to the dta */ parsfnm(line, &blk, 1); printf("%d %s\n", blk.fcb_drive, blk.fcb_name); /* request DOS services to create file */ if (bdosptr(0x16, &blk, 0) == -1) { perror("Error creating file"); exit(1); } /* save old dta and set new dta */ save_dta = getdta(); setdta(buffer); /* write new records */ blk.fcb_recsize = 256; blk.fcb_random = 0L; result = randbwr(&blk, 1); printf("result = %d\n", result); if (!result) printf("Write OK\n"); else { perror("Disk error"); exit(1); } /* request DOS services to close the file */ if (bdosptr(0x10, &blk, 0) == -1) { perror("Error closing file"); exit(1); } /* reset the old dta */ setdta(save_dta); return 0; } 函数名: setfillpattern 功 能: 选择用户定义的填充模式 用 法: void far setfillpattern(char far *upattern, int color); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; /* a user defined fill pattern */ char pattern[8] = {0x00, 0x70, 0x20, 0x27, 0x24, 0x24, 0x07, 0x00}; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy(); setcolor(getmaxcolor()); /* select a user defined fill pattern */ setfillpattern(pattern, getmaxcolor()); /* fill the screen with the pattern */ bar(0, 0, maxx, maxy); /* clean up */ getch(); closegraph(); return 0; } 函数名: setfillstyle 功 能: 设置填充模式和颜色 用 法: void far setfillstyle(int pattern, int color); 程序例: #include #include #include #include #include /* the names of the fill styles supported */ char *fname[] = { "EMPTY_FILL", "SOLID_FILL", "LINE_FILL", "LTSLASH_FILL", "SLASH_FILL", "BKSLASH_FILL", "LTBKSLASH_FILL", "HATCH_FILL", "XHATCH_FILL", "INTERLEAVE_FILL", "WIDE_DOT_FILL", "CLOSE_DOT_FILL", "USER_FILL" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int style, midx, midy; char stylestr[40]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; for (style = EMPTY_FILL; style < USER_FILL; style++) { /* select the fill style */ setfillstyle(style, getmaxcolor()); /* convert style into a string */ strcpy(stylestr, fname[style]); /* fill a bar */ bar3d(0, 0, midx-10, midy, 0, 0); /* output a message */ outtextxy(midx, midy, stylestr); /* wait for a key */ getch(); cleardevice(); } /* clean up */ getch(); closegraph(); return 0; } 函数名: setftime 功 能: 设置文件日期和时间 用 法: int setftime(int handle, struct ftime *ftimep); 程序例: #include #include #include #include int main(void) { struct ftime filet; FILE *fp; if ((fp = fopen("TEST.$$$", "w")) == NULL) { perror("Error:"); exit(1); } fprintf(fp, "testing...\n"); /* load ftime structure with new time and date */ filet.ft_tsec = 1; filet.ft_min = 1; filet.ft_hour = 1; filet.ft_day = 1; filet.ft_month = 1; filet.ft_year = 21; /* show current directory for time and date */ system("dir TEST.$$$"); /* change the time and date stamp*/ setftime(fileno(fp), &filet); /* close and remove the temporary file */ fclose(fp); system("dir TEST.$$$"); unlink("TEST.$$$"); return 0; } 函数名: setgraphbufsize 功 能: 改变内部图形缓冲区的大小 用 法: unsigned far setgraphbufsize(unsigned bufsize); 程序例: #include #include #include #include #define BUFSIZE 1000 /* internal graphics buffer size */ int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int x, y, oldsize; char msg[80]; /* set the size of the internal graphics buffer */ /* before making a call to initgraph. */ oldsize = setgraphbufsize(BUFSIZE); /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output some messages */ sprintf(msg, "Graphics buffer size: %d", BUFSIZE); settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, msg); sprintf(msg, "Old graphics buffer size: %d", oldsize); outtextxy(x, y+textheight("W"), msg); /* clean up */ getch(); closegraph(); return 0; } 函数名: setgraphmode 功 能: 将系统设置成图形模式且清屏 用 法: void far setgraphmode(int mode); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int x, y; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "Press any key to exit graphics:"); getch(); /* restore system to text mode */ restorecrtmode(); printf("We're now in text mode.\n"); printf("Press any key to return to graphics mode:"); getch(); /* return to graphics mode */ setgraphmode(getgraphmode()); /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "We're back in graphics mode."); outtextxy(x, y+textheight("W"), "Press any key to halt:"); /* clean up */ getch(); closegraph(); return 0; } 函数名: setjmp 功 能: 非局部转移 用 法: int setjmp(jmp_buf env); 程序例: #include #include #include void subroutine(void); jmp_buf jumper; int main(void) { int value; value = setjmp(jumper); if (value != 0) { printf("Longjmp with value %d\n", value); exit(value); } printf("About to call subroutine ... \n"); subroutine(); return 0; } void subroutine(void) { longjmp(jumper,1); } 函数名: setlinestyle 功 能: 设置当前画线宽度和类型 用 法: void far setlinestyle(int linestype, unsigned upattern); 程序例: #include #include #include #include #include /* the names of the line styles supported */ char *lname[] = { "SOLID_LINE", "DOTTED_LINE", "CENTER_LINE", "DASHED_LINE", "USERBIT_LINE" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int style, midx, midy, userpat; char stylestr[40]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* a user defined line pattern */ /* binary: "0000000000000001" */ userpat = 1; for (style=SOLID_LINE; style<=USERBIT_LINE; style++) { /* select the line style */ setlinestyle(style, userpat, 1); /* convert style into a string */ strcpy(stylestr, lname[style]); /* draw a line */ line(0, 0, midx-10, midy); /* draw a rectangle */ rectangle(0, 0, getmaxx(), getmaxy()); /* output a message */ outtextxy(midx, midy, stylestr); /* wait for a key */ getch(); cleardevice(); } /* clean up */ closegraph(); return 0; } 函数名: setmem 功 能: 存值到存储区 用 法: void setmem(void *addr, int len, char value); 程序例: #include #include #include int main(void) { char *dest; dest = calloc(21, sizeof(char)); setmem(dest, 20, 'c'); printf("%s\n", dest); return 0; } 函数名: setmode 功 能: 设置打开文件方式 用 法: int setmode(int handle, unsigned mode); 程序例: #include #include #include int main(void) { int result; result = setmode(fileno(stdprn), O_TEXT); if (result == -1) perror("Mode not available\n"); else printf("Mode successfully switched\n"); return 0; } 函数名: setpalette 功 能: 改变调色板的颜色 用 法: void far setpalette(int index, int actural_color); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int color, maxcolor, ht; int y = 10; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxcolor = getmaxcolor(); ht = 2 * textheight("W"); /* display the default colors */ for (color=1; color<=maxcolor; color++) { setcolor(color); sprintf(msg, "Color: %d", color); outtextxy(1, y, msg); y += ht; } /* wait for a key */ getch(); /* black out the colors one by one */ for (color=1; color<=maxcolor; color++) { setpalette(color, BLACK); getch(); } /* clean up */ closegraph(); return 0; } 函数名: setrgbpalette 功 能: 定义IBM8514图形卡的颜色 用 法: void far setrgbpalette(int colornum, int red, int green, int blue); 程序例: #include #include #include #include int main(void) { /* select a driver and mode that supports the use */ /* of the setrgbpalette function. */ int gdriver = VGA, gmode = VGAHI, errorcode; struct palettetype pal; int i, ht, y, xmax; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* grab a copy of the palette */ getpalette(&pal); /* create gray scale */ for (i=0; i setrgbpalette(pal.colors[i], i*4, i*4, i*4); /* display the gray scale */ ht = getmaxy() / 16; xmax = getmaxx(); y = 0; for (i=0; i { setfillstyle(SOLID_FILL, i); bar(0, y, xmax, y+ht); y += ht; } /* clean up */ getch(); closegraph(); return 0; } 函数名: settextjustify 功 能: 为图形函数设置文本的对齐方式 用 法: void far settextjustify(int horiz, int vert); 程序例: #include #include #include #include /* function prototype */ void xat(int x, int y); /* horizontal text justification settings */ char *hjust[] = { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" }; /* vertical text justification settings */ char *vjust[] = { "LEFT_TEXT", "CENTER_TEXT", "RIGHT_TEXT" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, hj, vj; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through text justifications */ for (hj=LEFT_TEXT; hj<=RIGHT_TEXT; hj++) for (vj=LEFT_TEXT; vj<=RIGHT_TEXT; vj++) { cleardevice(); /* set the text justification */ settextjustify(hj, vj); /* create a message string */ sprintf(msg, "%s %s", hjust[hj], vjust[vj]); /* create cross hairs on the screen */ xat(midx, midy); /* output the message */ outtextxy(midx, midy, msg); getch(); } /* clean up */ closegraph(); return 0; } /* draw an "x" at (x, y) */ void xat(int x, int y) { line(x-4, y, x+4, y); line(x, y-4, x, y+4); } 函数名: settextstyle 功 能: 为图形输出设置当前的文本属性 用 法: void far settextstyle (int font, int direction, char size); 程序例: #include #include #include #include /* the names of the text styles supported */ char *fname[] = { "DEFAULT font", "TRIPLEX font", "SMALL font", "SANS SERIF font", "GOTHIC font" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int style, midx, midy; int size = 1; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; settextjustify(CENTER_TEXT, CENTER_TEXT); /* loop through the available text styles */ for (style=DEFAULT_FONT; style<=GOTHIC_FONT; style++) { cleardevice(); if (style == TRIPLEX_FONT) size = 4; /* select the text style */ settextstyle(style, HORIZ_DIR, size); /* output a message */ outtextxy(midx, midy, fname[style]); getch(); } /* clean up */ closegraph(); return 0; } 函数名: settextstyle 功 能: 为图形输出设置当前的文本属性 用 法: void far settextstyle (int font, int direction, char size); 程序例: #include #include #include #include /* the names of the text styles supported */ char *fname[] = { "DEFAULT font", "TRIPLEX font", "SMALL font", "SANS SERIF font", "GOTHIC font" }; int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int style, midx, midy; int size = 1; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; settextjustify(CENTER_TEXT, CENTER_TEXT); /* loop through the available text styles */ for (style=DEFAULT_FONT; style<=GOTHIC_FONT; style++) { cleardevice(); if (style == TRIPLEX_FONT) size = 4; /* select the text style */ settextstyle(style, HORIZ_DIR, size); /* output a message */ outtextxy(midx, midy, fname[style]); getch(); } /* clean up */ closegraph(); return 0; } 函数名: settime 功 能: 设置系统时间 用 法: void settime(struct time *timep); 程序例: #include #include int main(void) { struct time t; gettime(&t); printf("The current minute is: %d\n", t.ti_min); printf("The current hour is: %d\n", t.ti_hour); printf("The current hundredth of a second is: %d\n", t.ti_hund); printf("The current second is: %d\n", t.ti_sec); /* Add one to the minutes struct element and then call settime */ t.ti_min++; settime(&t); return 0; } 函数名: setusercharsize 功 能: 为矢量字体改变字符宽度和高度 用 法: void far setusercharsize(int multx, int dirx, int multy, int diry); 程序例: #include #include #include #include int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* select a text style */ settextstyle(TRIPLEX_FONT, HORIZ_DIR, 4); /* move to the text starting position */ moveto(0, getmaxy() / 2); /* output some normal text */ outtext("Norm "); /* make the text 1/3 the normal width */ setusercharsize(1, 3, 1, 1); outtext("Short "); /* make the text 3 times normal width */ setusercharsize(3, 1, 1, 1); outtext("Wide"); /* clean up */ getch(); closegraph(); return 0; } 函数名: setvbuf 功 能: 把缓冲区与流相关 用 法: int setvbuf(FILE *stream, char *buf, int type, unsigned size); 程序例: #include int main(void) { FILE *input, *output; char bufr[512]; input = fopen("file.in", "r+b"); output = fopen("file.out", "w"); /* set up input stream for minimal disk access, using our own character buffer */ if (setvbuf(input, bufr, _IOFBF, 512) != 0) printf("failed to set up buffer for input file\n"); else printf("buffer set up for input file\n"); /* set up output stream for line buffering using space that will be obtained through an indirect call to malloc */ if (setvbuf(output, NULL, _IOLBF, 132) != 0) printf("failed to set up buffer for output file\n"); else printf("buffer set up for output file\n"); /* perform file I/O here */ /* close files */ fclose(input); fclose(output); return 0; } 函数名: setvect 功 能: 设置中断矢量入口 用 法: void setvect(int intr_num, void interrupt(*isr)()); 程序例: /***NOTE: This is an interrupt service routine. You can NOT compile this program with Test Stack Overflow turned on and get an executable file which will operate correctly. */ #include #include #include #define INTR 0X1C /* The clock tick interrupt */ void interrupt ( *oldhandler)(void); int count=0; void interrupt handler(void) { /* increase the global counter */ count++; /* call the old routine */ oldhandler(); } int main(void) { /* save the old interrupt vector */ oldhandler = getvect(INTR); /* install the new interrupt handler */ setvect(INTR, handler); /* loop until the counter exceeds 20 */ while (count < 20) printf("count is %d\n",count); /* reset the old interrupt handler */ setvect(INTR, oldhandler); return 0; } 函数名: setverify 功 能: 设置验证状态 用 法: void setverify(int value); 程序例: #include #include #include int main(void) { int verify_flag; printf("Enter 0 to set verify flag off\n"); printf("Enter 1 to set verify flag on\n"); verify_flag = getch() - 0; setverify(verify_flag); if (getverify()) printf("DOS verify flag is on\n"); else printf("DOS verify flag is off\n"); return 0; } 函数名: setviewport 功 能: 为图形输出设置当前视口 用 法: void far setviewport(int left, int top, int right, int bottom, int clipflag); 程序例: #include #include #include #include #define CLIP_ON 1 /* activates clipping in viewport */ int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } setcolor(getmaxcolor()); /* message in default full-screen viewport */ outtextxy(0, 0, "* <-- (0, 0) in default viewport"); /* create a smaller viewport */ setviewport(50, 50, getmaxx()-50, getmaxy()-50, CLIP_ON); /* display some text */ outtextxy(0, 0, "* <-- (0, 0) in smaller viewport"); /* clean up */ getch(); closegraph(); return 0; } 函数名: setvisualpage 功 能: 设置可见图形页号 用 法: void far setvisualpage(int pagenum); 程序例: #include #include #include #include int main(void) { /* select a driver and mode that supports */ /* multiple pages. */ int gdriver = EGA, gmode = EGAHI, errorcode; int x, y, ht; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; ht = textheight("W"); /* select the off screen page for drawing */ setactivepage(1); /* draw a line on page #1 */ line(0, 0, getmaxx(), getmaxy()); /* output a message on page #1 */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "This is page #1:"); outtextxy(x, y+ht, "Press any key to halt:"); /* select drawing to page #0 */ setactivepage(0); /* output a message on page #0 */ outtextxy(x, y, "This is page #0."); outtextxy(x, y+ht, "Press any key to view page #1:"); getch(); /* select page #1 as the visible page */ setvisualpage(1); /* clean up */ getch(); closegraph(); return 0; } 函数名: setwritemode 功 能: 设置图形方式下画线的输出模式 用 法: void far setwritemode(int mode); 程序例: #include #include #include #include int main() { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int xmax, ymax; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } xmax = getmaxx(); ymax = getmaxy(); /* select XOR drawing mode */ setwritemode(XOR_PUT); /* draw a line */ line(0, 0, xmax, ymax); getch(); /* erase the line by drawing over it */ line(0, 0, xmax, ymax); getch(); /* select overwrite drawing mode */ setwritemode(COPY_PUT); /* draw a line */ line(0, 0, xmax, ymax); /* clean up */ getch(); closegraph(); return 0; } 函数名: signal 功 能: 设置某一信号的对应动作 用 法: int signal(int sig, sigfun fname); 程序例: /* This example installs a signal handler routine for SIGFPE, catches an integer overflow condition, makes an adjustment to AX register, and returns. This example program MAY cause your computer to crash, and will produce runtime errors depending on which memory model is used. */ #pragma inline #include #include void Catcher(int sig, int type, int *reglist) { printf("Caught it!\n"); *(reglist + 8) = 3; /* make return AX = 3 */ } int main(void) { signal(SIGFPE, Catcher); asm mov ax,07FFFH /* AX = 32767 */ asm inc ax /* cause overflow */ asm into /* activate handler */ /* The handler set AX to 3 on return. If that hadn't happened, there would have been another exception when the next 'into' was executed after the 'dec' instruction. */ asm dec ax /* no overflow now */ asm into /* doesn't activate */ return 0; } 函数名: sin 功 能: 正弦函数 用 法: double sin(double x); 程序例: #include #include int main(void) { double result, x = 0.5; result = sin(x); printf("The sin() of %lf is %lf\n", x, result); return 0; } 函数名: sinh 功 能: 双曲正弦函数 用 法: double sinh(double x); 程序例: #include #include int main(void) { double result, x = 0.5; result = sinh(x); printf("The hyperbolic sin() of %lf is %lf\n", x, result); return 0; } 函数名: sleep 功 能: 执行挂起一段时间 用 法: unsigned sleep(unsigned seconds); 程序例: #include #include int main(void) { int i; for (i=1; i<5; i++) { printf("Sleeping for %d seconds\n", i); sleep(i); } return 0; } 函数名: sopen 功 能: 打开一共享文件 用 法: int sopen(char *pathname, int access, int shflag, int permiss); 程序例: #include #include #include #include #include #include int main(void) { int handle; int status; handle = sopen("c:\\autoexec.bat", O_RDONLY, SH_DENYNO, S_IREAD); if (!handle) { printf("sopen failed\n"); exit(1); } status = access("c:\\autoexec.bat", 6); if (status == 0) printf("read/write access allowed\n"); else printf("read/write access not allowed\n"); close(handle); return 0; } 函数名: sound 功 能: 以指定频率打开PC扬声器 用 法: void sound(unsigned frequency); 程序例: /* Emits a 7-Hz tone for 10 seconds. Your PC may not be able to emit a 7-Hz tone. */ #include int main(void) { sound(7); delay(10000); nosound(); return 0; } 函数名: spawnl 功 能: 创建并运行子程序 用 法: int spawnl(int mode, char *pathname, char *arg0, arg1, ... argn, NULL); 程序例: #include #include #include int main(void) { int result; clrscr(); result = spawnl(P_WAIT, "tcc.exe", NULL); if (result == -1) { perror("Error from spawnl"); exit(1); } return 0; } 函数名: spawnle 功 能: 创建并运行子程序 用 法: int spawnle(int mode, char *pathname, char *arg0, arg1,..., argn, NULL); 程序例: /* spawnle() example */ #include #include #include int main(void) { int result; clrscr(); result = spawnle(P_WAIT, "tcc.exe", NULL, NULL); if (result == -1) { perror("Error from spawnle"); exit(1); } return 0; } 函数名: sprintf 功 能: 送格式化输出到字符串中 用 法: int sprintf(char *string, char *farmat [,argument,...]); 程序例: #include #include int main(void) { char buffer[80]; sprintf(buffer, "An approximation of Pi is %f\n", M_PI); puts(buffer); return 0; } 函数名: sqrt 功 能: 计算平方根 用 法: double sqrt(double x); 程序例: #include #include int main(void) { double x = 4.0, result; result = sqrt(x); printf("The square root of %lf is %lf\n", x, result); return 0; } 函数名: srand 功 能: 初始化随机数发生器 用 法: void srand(unsigned seed); 程序例: #include #include #include int main(void) { int i; time_t t; srand((unsigned) time(&t)); printf("Ten random numbers from 0 to 99\n\n"); for(i=0; i<10; i++) printf("%d\n", rand() % 100); return 0; } 函数名: sscanf 功 能: 执行从字符串中的格式化输入 用 法: int sscanf(char *string, char *format[,argument,...]); 程序例: #include #include int main(void) { char label[20]; char name[20]; int entries = 0; int loop, age; double salary; struct Entry_struct { char name[20]; int age; float salary; } entry[20]; /* Input a label as a string of characters restricting to 20 characters */ printf("\n\nPlease enter a label for the chart: "); scanf("%20s", label); fflush(stdin); /* flush the input stream in case of bad input */ /* Input number of entries as an integer */ printf("How many entries will there be? (less than 20) "); scanf("%d", &entries); fflush(stdin); /* flush the input stream in case of bad input */ /* input a name restricting input to only letters upper or lower case */ for (loop=0;loop { printf("Entry %d\n", loop); printf(" Name : "); scanf("%[A-Za-z]", entry[loop].name); fflush(stdin); /* flush the input stream in case of bad input */ /* input an age as an integer */ printf(" Age : "); scanf("%d", &entry[loop].age); fflush(stdin); /* flush the input stream in case of bad input */ /* input a salary as a float */ printf(" Salary : "); scanf("%f", &entry[loop].salary); fflush(stdin); /* flush the input stream in case of bad input */ } /* Input a name, age and salary as a string, integer, and double */ printf("\nPlease enter your name, age and salary\n"); scanf("%20s %d %lf", name, &age, &salary); /* Print out the data that was input */ printf("\n\nTable %s\n",label); printf("Compiled by %s age %d $%15.2lf\n", name, age, salary); printf("-----------------------------------------------------\n"); for (loop=0;loop printf("%4d | %-20s | %5d | %15.2lf\n", loop + 1, entry[loop].name, entry[loop].age, entry[loop].salary); printf("-----------------------------------------------------\n"); return 0; } 函数名: stat 功 能: 读取打开文件信息 用 法: int stat(char *pathname, struct stat *buff); 程序例: #include #include #include #define FILENAME "TEST.$$$" int main(void) { struct stat statbuf; FILE *stream; /* open a file for update */ if ((stream = fopen(FILENAME, "w+")) == NULL) { fprintf(stderr, "Cannot open output file.\n"); return(1); } /* get information about the file */ stat(FILENAME, &statbuf); fclose(stream); /* display the information returned */ if (statbuf.st_mode & S_IFCHR) printf("Handle refers to a device.\n"); if (statbuf.st_mode & S_IFREG) printf("Handle refers to an ordinary file.\n"); if (statbuf.st_mode & S_IREAD) printf("User has read permission on file.\n"); if (statbuf.st_mode & S_IWRITE) printf("User has write permission on file.\n"); printf("Drive letter of file: %c\n", 'A'+statbuf.st_dev); printf("Size of file in bytes: %ld\n", statbuf.st_size); printf("Time file last opened: %s\n", ctime(&statbuf.st_ctime)); return 0; } 函数名: _status87 功 能: 取浮点状态 用 法: unsigned int _status87(void); 程序例: #include #include int main(void) { float x; double y = 1.5e-100; printf("Status 87 before error: %x\n", _status87()); x = y; /* <-- force an error to occur */ y = x; printf("Status 87 after error : %x\n", _status87()); return 0; } 函数名: stime 功 能: 设置时间 用 法: int stime(long *tp); 程序例: #include #include #include int main(void) { time_t t; struct tm *area; t = time(NULL); area = localtime(&t); printf("Number of seconds since 1/1/1970 is: %ld\n", t); printf("Local time is: %s", asctime(area)); t++; area = localtime(&t); printf("Add a second: %s", asctime(area)); t += 60; area = localtime(&t); printf("Add a minute: %s", asctime(area)); t += 3600; area = localtime(&t); printf("Add an hour: %s", asctime(area)); t += 86400L; area = localtime(&t); printf("Add a day: %s", asctime(area)); t += 2592000L; area = localtime(&t); printf("Add a month: %s", asctime(area)); t += 31536000L; area = localtime(&t); printf("Add a year: %s", asctime(area)); return 0; } 函数名: stpcpy 功 能: 拷贝一个字符串到另一个 用 法: char *stpcpy(char *destin, char *source); 程序例: #include #include int main(void) { char string[10]; char *str1 = "abcdefghi"; stpcpy(string, str1); printf("%s\n", string); return 0; } 函数名: strcat 功 能: 字符串拼接函数 用 法: char *strcat(char *destin, char *source); 程序例: #include #include int main(void) { char destination[25]; char *blank = " ", *c = "C++", *Borland = "Borland"; strcpy(destination, Borland); strcat(destination, blank); strcat(destination, c); printf("%s\n", destination); return 0; } 函数名: strchr 功 能: 在一个串中查找给定字符的第一个匹配之处\ 用 法: char *strchr(char *str, char c); 程序例: #include #include int main(void) { char string[15]; char *ptr, c = 'r'; strcpy(string, "This is a string"); ptr = strchr(string, c); if (ptr) printf("The character %c is at position: %d\n", c, ptr-string); else printf("The character was not found\n"); return 0; } 函数名: strcmp 功 能: 串比较 用 法: int strcmp(char *str1, char *str2); 程序例: #include #include int main(void) { char *buf1 = "aaa", *buf2 = "bbb", *buf3 = "ccc"; int ptr; ptr = strcmp(buf2, buf1); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); else printf("buffer 2 is less than buffer 1\n"); ptr = strcmp(buf2, buf3); if (ptr > 0) printf("buffer 2 is greater than buffer 3\n"); else printf("buffer 2 is less than buffer 3\n"); return 0; } 函数名: strncmpi 功 能: 将一个串中的一部分与另一个串比较, 不管大小写 用 法: int strncmpi(char *str1, char *str2, unsigned maxlen); 程序例: #include #include int main(void) { char *buf1 = "BBB", *buf2 = "bbb"; int ptr; ptr = strcmpi(buf2, buf1); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); if (ptr < 0) printf("buffer 2 is less than buffer 1\n"); if (ptr == 0) printf("buffer 2 equals buffer 1\n"); return 0; } 函数名: strcpy 功 能: 串拷贝 用 法: char *strcpy(char *str1, char *str2); 程序例: #include #include int main(void) { char string[10]; char *str1 = "abcdefghi"; strcpy(string, str1); printf("%s\n", string); return 0; } 函数名: strcspn 功 能: 在串中查找第一个给定字符集内容的段 用 法: int strcspn(char *str1, char *str2); 程序例: #include #include #include int main(void) { char *string1 = "1234567890"; char *string2 = "747DC8"; int length; length = strcspn(string1, string2); printf("Character where strings intersect is at position %d\n", length); return 0; } 函数名: strdup 功 能: 将串拷贝到新建的位置处 用 法: char *strdup(char *str); 程序例: #include #include #include int main(void) { char *dup_str, *string = "abcde"; dup_str = strdup(string); printf("%s\n", dup_str); free(dup_str); return 0; } 函数名: stricmp 功 能: 以大小写不敏感方式比较两个串 用 法: int stricmp(char *str1, char *str2); 程序例: #include #include int main(void) { char *buf1 = "BBB", *buf2 = "bbb"; int ptr; ptr = stricmp(buf2, buf1); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); if (ptr < 0) printf("buffer 2 is less than buffer 1\n"); if (ptr == 0) printf("buffer 2 equals buffer 1\n"); return 0; } 函数名: strerror 功 能: 返回指向错误信息字符串的指针 用 法: char *strerror(int errnum); 程序例: #include #include int main(void) { char *buffer; buffer = strerror(errno); printf("Error: %s\n", buffer); return 0; } 函数名: strcmpi 功 能: 将一个串与另一个比较, 不管大小写 用 法: int strcmpi(char *str1, char *str2); 程序例: #include #include int main(void) { char *buf1 = "BBB", *buf2 = "bbb"; int ptr; ptr = strcmpi(buf2, buf1); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); if (ptr < 0) printf("buffer 2 is less than buffer 1\n"); if (ptr == 0) printf("buffer 2 equals buffer 1\n"); return 0; } 函数名: strncmp 功 能: 串比较 用 法: int strncmp(char *str1, char *str2, int maxlen); 程序例: #include #include int main(void) { char *buf1 = "aaabbb", *buf2 = "bbbccc", *buf3 = "ccc"; int ptr; ptr = strncmp(buf2,buf1,3); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); else printf("buffer 2 is less than buffer 1\n"); ptr = strncmp(buf2,buf3,3); if (ptr > 0) printf("buffer 2 is greater than buffer 3\n"); else printf("buffer 2 is less than buffer 3\n"); return(0); } 函数名: strncmpi 功 能: 把串中的一部分与另一串中的一部分比较, 不管大小写 用 法: int strncmpi(char *str1, char *str2); 程序例: #include #include int main(void) { char *buf1 = "BBBccc", *buf2 = "bbbccc"; int ptr; ptr = strncmpi(buf2,buf1,3); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); if (ptr < 0) printf("buffer 2 is less than buffer 1\n"); if (ptr == 0) printf("buffer 2 equals buffer 1\n"); return 0; } 函数名: strncpy 功 能: 串拷贝 用 法: char *strncpy(char *destin, char *source, int maxlen); 程序例: #include #include int main(void) { char string[10]; char *str1 = "abcdefghi"; strncpy(string, str1, 3); string[3] = '\0'; printf("%s\n", string); return 0; } 函数名: strnicmp 功 能: 不注重大小写地比较两个串 用 法: int strnicmp(char *str1, char *str2, unsigned maxlen); 程序例: #include #include int main(void) { char *buf1 = "BBBccc", *buf2 = "bbbccc"; int ptr; ptr = strnicmp(buf2, buf1, 3); if (ptr > 0) printf("buffer 2 is greater than buffer 1\n"); if (ptr < 0) printf("buffer 2 is less than buffer 1\n"); if (ptr == 0) printf("buffer 2 equals buffer 1\n"); return 0; } 函数名: strnset 功 能: 将一个串中的所有字符都设为指定字符 用 法: char *strnset(char *str, char ch, unsigned n); 程序例: #include #include int main(void) { char *string = "abcdefghijklmnopqrstuvwxyz"; char letter = 'x'; printf("string before strnset: %s\n", string); strnset(string, letter, 13); printf("string after strnset: %s\n", string); return 0; } 函数名: strpbrk 功 能: 在串中查找给定字符集中的字符 用 法: char *strpbrk(char *str1, char *str2); 程序例: #include #include int main(void) { char *string1 = "abcdefghijklmnopqrstuvwxyz"; char *string2 = "onm"; char *ptr; ptr = strpbrk(string1, string2); if (ptr) printf("strpbrk found first character: %c\n", *ptr); else printf("strpbrk didn't find character in set\n"); return 0; } 函数名: strrchr 功 能: 在串中查找指定字符的最后一个出现 用 法: char *strrchr(char *str, char c); 程序例: #include #include int main(void) { char string[15]; char *ptr, c = 'r'; strcpy(string, "This is a string"); ptr = strrchr(string, c); if (ptr) printf("The character %c is at position: %d\n", c, ptr-string); else printf("The character was not found\n"); return 0; } 函数名: strrev 功 能: 串倒转 用 法: char *strrev(char *str); 程序例: #include #include int main(void) { char *forward = "string"; printf("Before strrev(): %s\n", forward); strrev(forward); printf("After strrev(): %s\n", forward); return 0; } 函数名: strset 功 能: 将一个串中的所有字符都设为指定字符 用 法: char *strset(char *str, char c); 程序例: #include #include int main(void) { char string[10] = "123456789"; char symbol = 'c'; printf("Before strset(): %s\n", string); strset(string, symbol); printf("After strset(): %s\n", string); return 0; } 函数名: strspn 功 能: 在串中查找指定字符集的子集的第一次出现 用 法: int strspn(char *str1, char *str2); 程序例: #include #include #include int main(void) { char *string1 = "1234567890"; char *string2 = "123DC8"; int length; length = strspn(string1, string2); printf("Character where strings differ is at position %d\n", length); return 0; } 函数名: strstr 功 能: 在串中查找指定字符串的第一次出现 用 法: char *strstr(char *str1, char *str2); 程序例: #include #include int main(void) { char *str1 = "Borland International", *str2 = "nation", *ptr; ptr = strstr(str1, str2); printf("The substring is: %s\n", ptr); return 0; } 函数名: strtod 功 能: 将字符串转换为double型值 用 法: double strtod(char *str, char **endptr); 程序例: #include #include int main(void) { char input[80], *endptr; double value; printf("Enter a floating point number:"); gets(input); value = strtod(input, &endptr); printf("The string is %s the number is %lf\n", input, value); return 0; } 函数名: strtok 功 能: 查找由在第二个串中指定的分界符分隔开的单词 用 法: char *strtok(char *str1, char *str2); 程序例: #include #include int main(void) { char input[16] = "abc,d"; char *p; /* strtok places a NULL terminator in front of the token, if found */ p = strtok(input, ","); if (p) printf("%s\n", p); /* A second call to strtok using a NULL as the first parameter returns a pointer to the character following the token */ p = strtok(NULL, ","); if (p) printf("%s\n", p); return 0; } 函数名: strtol 功 能: 将串转换为长整数 用 法: long strtol(char *str, char **endptr, int base); 程序例: #include #include int main(void) { char *string = "87654321", *endptr; long lnumber; /* strtol converts string to long integer */ lnumber = strtol(string, &endptr, 10); printf("string = %s long = %ld\n", string, lnumber); return 0; } 函数名: strupr 功 能: 将串中的小写字母转换为大写字母 用 法: char *strupr(char *str); 程序例: #include #include int main(void) { char *string = "abcdefghijklmnopqrstuvwxyz", *ptr; /* converts string to upper case characters */ ptr = strupr(string); printf("%s\n", ptr); return 0; } 函数名: swab 功 能: 交换字节 用 法: void swab (char *from, char *to, int nbytes); 程序例: #include #include #include char source[15] = "rFna koBlrna d"; char target[15]; int main(void) { swab(source, target, strlen(source)); printf("This is target: %s\n", target); return 0; } 函数名: system 功 能: 发出一个DOS命令 用 法: int system(char *command); 程序例: #include #include int main(void) { printf("About to spawn command.com and run a DOS command\n"); system("dir"); return 0; } 函数大全(t开头) 函数名: tan 功 能: 正切函数 用 法: double tan(double x); 程序例: #include #include int main(void) { double result, x; x = 0.5; result = tan(x); printf("The tan of %lf is %lf\n", x, result); return 0; } 函数名: tanh 功 能: 双曲正切函数 用 法: double tanh(double x); 程序例: #include #include int main(void) { double result, x; x = 0.5; result = tanh(x); printf("The hyperbolic tangent of %lf is %lf\n", x, result); return 0; } 函数名: tell 功 能: 取文件指针的当前位置 用 法: long tell(int handle); 程序例: #include #include #include #include int main(void) { int handle; char msg[] = "Hello world"; if ((handle = open("TEST.$$$", O_CREAT | O_TEXT | O_APPEND)) == -1) { perror("Error:"); return 1; } write(handle, msg, strlen(msg)); printf("The file pointer is at byte %ld\n", tell(handle)); close(handle); return 0; } 函数名: textattr 功 能: 设置文本属性 用 法: void textattr(int attribute); 程序例: #include int main(void) { int i; clrscr(); for (i=0; i<9; i++) { textattr(i + ((i+1) << 4)); cprintf("This is a test\r\n"); } return 0; } 函数名: textbackground 功 能: 选择新的文本背景颜色 用 法: void textbackground(int color); 程序例: #include int main(void) { int i, j; clrscr(); for (i=0; i<9; i++) { for (j=0; j<80; j++) cprintf("C"); cprintf("\r\n"); textcolor(i+1); textbackground(i); } return 0; } 函数名: textcolor 功 能: 在文本模式中选择新的字符颜色 用 法: void textcolor(int color); 程序例: #include int main(void) { int i; for (i=0; i<15; i++) { textcolor(i); cprintf("Foreground Color\r\n"); } return 0; } 函数名: textheight 功 能: 返回以像素为单位的字符串高度 用 法: int far textheight(char far *textstring); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int y = 0; int i; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* draw some text on the screen */ for (i=1; i<11; i++) { /* select the text style, direction, and size */ settextstyle(TRIPLEX_FONT, HORIZ_DIR, i); /* create a message string */ sprintf(msg, "Size: %d", i); /* output the message */ outtextxy(1, y, msg); /* advance to the next text line */ y += textheight(msg); } /* clean up */ getch(); closegraph(); return 0; } 函数名: textmode 功 能: 将屏幕设置成文本模式 用 法: void textmode(int mode); 程序例: #include int main(void) { textmode(BW40); cprintf("ABC"); getch(); textmode(C40); cprintf("ABC"); getch(); textmode(BW80); cprintf("ABC"); getch(); textmode(C80); cprintf("ABC"); getch(); textmode(MONO); cprintf("ABC"); getch(); return 0; } 函数名: textwidth 功 能: 返回以像素为单位的字符串宽度 用 法: int far textwidth(char far *textstring); 程序例: #include #include #include #include int main(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; int x = 0, y = 0; int i; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } y = getmaxy() / 2; settextjustify(LEFT_TEXT, CENTER_TEXT); for (i=1; i<11; i++) { /* select the text style, direction, and size */ settextstyle(TRIPLEX_FONT, HORIZ_DIR, i); /* create a message string */ sprintf(msg, "Size: %d", i); /* output the message */ outtextxy(x, y, msg); /* advance to the end of the text */ x += textwidth(msg); } /* clean up */ getch(); closegraph(); return 0; } 函数名: time 功 能: 取一天的时间 用 法: logn time(long *tloc); 程序例: #include #include #include int main(void) { time_t t; t = time(NULL); printf("The number of seconds since January 1, 1970 is %ld",t); return 0; } 函数名: tmpfile 功 能: 以二进制方式打开暂存文件 用 法: FILE *tmpfile(void); 程序例: #include #include int main(void) { FILE *tempfp; tempfp = tmpfile(); if (tempfp) printf("Temporary file created\n"); else { printf("Unable to create temporary file\n"); exit(1); } return 0; } 函数名: tmpnam 功 能: 创建一个唯一的文件名 用 法: char *tmpnam(char *sptr); 程序例: #include int main(void) { char name[13]; tmpnam(name); printf("Temporary name: %s\n", name); return 0; } 函数名: tolower 功 能: 把字符转换成小写字母 用 法: int tolower(int c); 程序例: #include #include #include int main(void) { int length, i; char *string = "THIS IS A STRING"; length = strlen(string); for (i=0; i { string[i] = tolower(string[i]); } printf("%s\n",string); return 0; } 函数名: toupper 功 能: 把字符转换成大写字母 用 法: int toupper(int c); 程序例: #include #include #include int main(void) { int length, i; char *string = "this is a string"; length = strlen(string); for (i=0; i { string[i] = toupper(string[i]); } printf("%s\n",string); return 0; } 函数名: tzset 功 能: UNIX时间兼容函数 用 法: void tzset(void); 程序例: #include #include #include int main(void) { time_t td; putenv("TZ=PST8PDT"); tzset(); time(&td); printf("Current time = %s\n", asctime(localtime(&td))); return 0; } 函数大全(u开头) 函数名: ultoa 功 能: 转换一个无符号长整型数为字符串 用 法: char *ultoa(unsigned long value, char *string, int radix); 程序例: #include #include int main( void ) { unsigned long lnumber = 3123456789L; char string[25]; ultoa(lnumber,string,10); printf("string = %s unsigned long = %lu\n",string,lnumber); return 0; } 函数名: ungetc 功 能: 把一个字符退回到输入流中 用 法: int ungetc(char c, FILE *stream); 程序例: #include #include int main( void ) { int i=0; char ch; puts("Input an integer followed by a char:"); /* read chars until non digit or EOF */ while((ch = getchar()) != EOF && isdigit(ch)) i = 10 * i + ch - 48; /* convert ASCII into int value */ /* if non digit char was read, push it back into input buffer */ if (ch != EOF) ungetc(ch, stdin); printf("i = %d, next char in buffer = %c\n", i, getchar()); return 0; } 函数名: ungetch 功 能: 把一个字符退回到键盘缓冲区中 用 法: int ungetch(int c); 程序例: #include #include #include int main( void ) { int i=0; char ch; puts("Input an integer followed by a char:"); /* read chars until non digit or EOF */ while((ch = getche()) != EOF && isdigit(ch)) i = 10 * i + ch - 48; /* convert ASCII into int value */ /* if non digit char was read, push it back into input buffer */ if (ch != EOF) ungetch(ch); printf("\n\ni = %d, next char in buffer = %c\n", i, getch()); return 0; } 函数名: unixtodos 功 能: 把日期和时间转换成DOS格式 用 法: void unixtodos(long utime, struct date *dateptr, struct time *timeptr); 程序例: #include #include char *month[] = {"---", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; #define SECONDS_PER_DAY 86400L /* the number of seconds in one day */ struct date dt; struct time tm; int main(void) { unsigned long val; /* get today's date and time */ getdate(&dt); gettime(&tm); printf("today is %d %s %d\n", dt.da_day, month[dt.da_mon], dt.da_year); /* convert date and time to unix format (number of seconds since Jan 1, 1970 */ val = dostounix(&dt, &tm); /* subtract 42 days worth of seconds */ val -= (SECONDS_PER_DAY * 42); /* convert back to dos time and date */ unixtodos(val, &dt, &tm); printf("42 days ago it was %d %s %d\n", dt.da_day, month[dt.da_mon], dt.da_year); return 0; } 函数名: unlink 功 能: 删掉一个文件 用 法: int unlink(char *filename); 程序例: #include #include int main(void) { FILE *fp = fopen("junk.jnk","w"); int status; fprintf(fp,"junk"); status = access("junk.jnk",0); if (status == 0) printf("File exists\n"); else printf("File doesn't exist\n"); fclose(fp); unlink("junk.jnk"); status = access("junk.jnk",0); if (status == 0) printf("File exists\n"); else printf("File doesn't exist\n"); return 0; } 函数名: unlock 功 能: 解除文件共享锁 用 法: int unlock(int handle, long offset, long length); 程序例: #include #include #include #include #include #include int main(void) { int handle, status; long length; handle = sopen("c:\\autoexec.bat",O_RDONLY,SH_DENYNO,S_IREAD); if (handle < 0) { printf("sopen failed\n"); exit(1); } length = filelength(handle); status = lock(handle,0L,length/2); if (status == 0) printf("lock succeeded\n"); else printf("lock failed\n"); status = unlock(handle,0L,length/2); if (status == 0) printf("unlock succeeded\n"); else printf("unlock failed\n"); close(handle); return 0; } 函数大全(v开头) 函数名: vfprintf 功 能: 送格式化输出到一流中 用 法: int vfprintf(FILE *stream, char *format, va_list param); 程序例: #include #include #include FILE *fp; int vfpf(char *fmt, ...) { va_list argptr; int cnt; va_start(argptr, fmt); cnt = vfprintf(fp, fmt, argptr); va_end(argptr); return(cnt); } int main(void) { int inumber = 30; float fnumber = 90.0; char string[4] = "abc"; fp = tmpfile(); if (fp == NULL) { perror("tmpfile() call"); exit(1); } vfpf("%d %f %s", inumber, fnumber, string); rewind(fp); fscanf(fp,"%d %f %s", &inumber, &fnumber, string); printf("%d %f %s\n", inumber, fnumber, string); fclose(fp); return 0; } 函数名: vfscanf 功 能: 从流中执行格式化输入 用 法: int vfscanf(FILE *stream, char *format, va_list param); 程序例: #include #include #include FILE *fp; int vfsf(char *fmt, ...) { va_list argptr; int cnt; va_start(argptr, fmt); cnt = vfscanf(fp, fmt, argptr); va_end(argptr); return(cnt); } int main(void) { int inumber = 30; float fnumber = 90.0; char string[4] = "abc"; fp = tmpfile(); if (fp == NULL) { perror("tmpfile() call"); exit(1); } fprintf(fp,"%d %f %s\n",inumber,fnumber,string); rewind(fp); vfsf("%d %f %s",&inumber,&fnumber,string); printf("%d %f %s\n",inumber,fnumber,string); fclose(fp); return 0; } 函数名: vprintf 功 能: 送格式化输出到stdout中 用 法: int vprintf(char *format, va_list param); 程序例: #include #include int vpf(char *fmt, ...) { va_list argptr; int cnt; va_start(argptr, format); cnt = vprintf(fmt, argptr); va_end(argptr); return(cnt); } int main(void) { int inumber = 30; float fnumber = 90.0; char *string = "abc"; vpf("%d %f %s\n",inumber,fnumber,string); return 0; } 函数名: vscanf 功 能: 从stdin中执行格式化输入 用 法: int vscanf(char *format, va_list param); 程序例: #include #include #include int vscnf(char *fmt, ...) { va_list argptr; int cnt; printf("Enter an integer, a float, and a string (e.g. i,f,s,)\n"); va_start(argptr, fmt); cnt = vscanf(fmt, argptr); va_end(argptr); return(cnt); } int main(void) { int inumber; float fnumber; char string[80]; vscnf("%d, %f, %s", &inumber, &fnumber, string); printf("%d %f %s\n", inumber, fnumber, string); return 0; } 函数名: vsprintf 功 能: 送格式化输出到串中 用 法: int vsprintf(char *string, char *format, va_list param); 程序例: #include #include #include char buffer[80]; int vspf(char *fmt, ...) { va_list argptr; int cnt; va_start(argptr, fmt); cnt = vsprintf(buffer, fmt, argptr); va_end(argptr); return(cnt); } int main(void) { int inumber = 30; float fnumber = 90.0; char string[4] = "abc"; vspf("%d %f %s", inumber, fnumber, string); printf("%s\n", buffer); return 0; } 函数名: vsscanf 功 能: 从流中执行格式化输入 用 法: int vsscanf(char *s, char *format, va_list param); 程序例: #include #include #include char buffer[80] = "30 90.0 abc"; int vssf(char *fmt, ...) { va_list argptr; int cnt; fflush(stdin); va_start(argptr, fmt); cnt = vsscanf(buffer, fmt, argptr); va_end(argptr); return(cnt); } int main(void) { int inumber; float fnumber; char string[80]; vssf("%d %f %s", &inumber, &fnumber, string); printf("%d %f %s\n", inumber, fnumber, string); return 0; } 函数大全(w开头) 函数名: wherex 功 能: 返回窗口内水平光标位置 用 法: int wherex(void); 程序例: #include int main(void) { clrscr(); gotoxy(10,10); cprintf("Current location is X: %d Y: %d\r\n", wherex(), wherey()); getch(); return 0; } 函数名: wherey 功 能: 返回窗口内垂直光标位置 用 法: int wherey(void); 程序例: #include int main(void) { clrscr(); gotoxy(10,10); cprintf("Current location is X: %d Y: %d\r\n", wherex(), wherey()); getch(); return 0; } 函数名: window 功 能: 定义活动文本模式窗口 用 法: void window(int left, int top, int right, int bottom); 程序例: #include int main(void) { window(10,10,40,11); textcolor(BLACK); textbackground(WHITE); cprintf("This is a test\r\n"); return 0; } 函数名: write 功 能: 写到一文件中 用 法: int write(int handel, void *buf, int nbyte); 程序例: #include #include #include #include #include #include int main(void) { int handle; char string[40]; int length, res; /* Create a file named "TEST.$$$" in the current directory and write a string to it. If "TEST.$$$" already exists, it will be overwritten. */ if ((handle = open("TEST.$$$", O_WRONLY | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE)) == -1) { printf("Error opening file.\n"); exit(1); } strcpy(string, "Hello, world!\n"); length = strlen(string); if ((res = write(handle, string, length)) != length) { printf("Error writing to the file.\n"); exit(1); } printf("Wrote %d bytes to the file.\n", res); close(handle); return 0; } struct xfcb { char xfcb_flag; /* Contains 0xff to indicate xfcb */ char xfcb_resv[5]; /* Reserved for DOS */ char xfcb_attr; /* Search attribute */ struct fcb xfcb_fcb; /* The standard fcb */ };