程序设计(C语言)(常用函数说明)

来源:互联网 发布:单片机光耦隔离电路 编辑:程序博客网 时间:2024/06/07 21:39
  
程序设计(C语言)(常用函数说明)
                                                                                                                                                                                                                                    
                                                                                                                                                                                  

C语言程序设计(常用函数说明)
C 语言是1972年由美国的Dennis Ritchie设计发明的,并首次在UNIX操作系统的 DEC PDP-11计算机上使用。它由早期的编程语言 BCPL(Basic Combind Programming Language)发展演变而来。在1970年,AT&T贝尔实验室的 Ken Thompson根据BCPL语言设计出较先进的并取名为 B的语言, 最后导了C 语言的问世。随着微型计算机的日益普及, 出现了许多C 语言版本。由于没有统一的标准, 使得这些C 语言之间出现了一些不一致的地方。为了改变这种情况, 美国国家标准研究所(ANSI)为C 语言制定了一套ANSI标准, 成为现行的C语言标准。
第一章          C 语言的特点
C 语言发展如此迅速,而且成为最受欢迎的语言之一, 主要因为它具有强大的功能。许多著名的系统软件, 如DBASE Ⅲ PLUS、DBASE Ⅳ 都是由C 语言编写的。用C 语言加上一些汇编语言子程序, 就更能显示C 语言的优势了,象PC- DOS 、WORDSTAR等就是用这种方法编写的。归纳起来C 语言具有下列特点:
               C是中级语言
它把高级语言的基本结构和语句与低级语言的实用性结合起来。C 语言可以象汇编语言一样对位、字节和地址进行操作, 而这三者是计算机最基本的工作单元。
               C是结构式语言   
结构式语言的显著特点是代码及数据的分隔化, 即程序的各个部分除了必要的
信息交流外彼此独立。这种结构化方式可使程序层次清晰, 便于使用、维护以及调
试。C 语言是以函数形式提供给用户的,这些函数可方便的调用并具有多种循环、条件语句控制程序流向,从而使程序完全结构化。
               C语言功能齐全
   C 语言具有各种各样的数据类型, 并引入了指针概念, 可使程序效率更高。另
外C 语言也具有强大的图形功能, 支持多种显示器和驱动器。而且计算功能、逻辑
判断功能也比较强大, 可以实现决策目的。
               C语言适用范围大
   C 语言还有一个突出的优点就是适合于多种操作系统, 如DOS、UNIX,也适用于
多种机型。
第二章          数据类型、变量和运算符
Turbo C程序的一般组成部分 请看下面一段Turbo C源程序。
    例1:
    /*Example program of Turbo C*/
    #include <stdio.h>                       /*
包含文件说明*/
    void lgc(void);                          /*子函数说明*/
    char answer;                             /*定义全程变量*/
    int main()                               /*主函数定义*/
    {
          char a;                            /*
定义局部变量*/
          clrscr();
          gotoxy(12,3);
          puts("Welcome to use Turbo C2.0!");
          gotoxy(15, 13);
          printf("<Esc>--Exit");
          gotoxy(15, 15);
          printf("<CR>--Continue");
          while(1)
          {
            a=getch();
            if(a==27)
               break;
            if(a==13)
            {
               lgc();
               if(answer=='y'||answer=='Y')
               {
                 gotoxy(23,14);
                 puts("Please Write to the Company");
                 getch();
                 break;
               }
            }
          }
          return(0);
    }
    void lgc(void)
    {
       clrscr();
       gotoxy(12,8);
       printf("The Excellent Selection!");
       gotoxy(21,12);
       printf("Do you have any question?(Y/N)");
       answer=getche();
    }
   
由例子程序可以看出, Turbo C源程序主要有以下几个特点:
    (1). 程序一般用小写字母书写;
    (2). 大多数语句结尾必须要用";"作为终止符, 否则Turbo C 不认为该语句结束;
    (3). 每个程序必须有一个而且只能有一个称作主函数的main()函数;
    (4). 每个程序体 (主函数和每个子函数, 如上例中的main()函数和sub()函数)必须用一对花括号"{"和"}"括起来;
    (5). 一个较完整的程序大致包括:包含文件(一组#include<*.h>语句)、用户函数说明部分、全程变量定义、主函数和若干子函数组成。在主函数和子函数中又包括局部变量定义、若干个Turbo C库函数、控制流程语句、 用户函数的调用语句等;
    (6). 注释部分包含在"/*"和"*/"之间, 在编译时它被Turbo C编译器忽略。
    (7).变量的标识一般采用匈牙利表示的方法,即通常在变量面前再加上变量类型
第一个字符.
说明:
    (1). 象其它一些语言一样, Turbo C的变量在使用之前必须先定义其数据类型,
未经定义的变量不能使用。定义变量类型应在可执行语句前面, 如上例main()函
数中的第一条语句就是变量定义语句, 它必须放在第一各执行语句clrscr()前面。
    (2). 在Turbo C中, 大、小写字母是有区别的, 相同字母的大、小写代表不同
的变量。
      用Turbo C编程时, 一行一条语句, 遇到嵌套语句向后缩进,必要时对程序加上注释行。这样可以便程序结构清楚、易于阅读、维护和修改。
    通过以上介绍, 可以得出Turbo C源程序的一般形式为:
          包含文件
          子函数类型说明
          全程变量定义
          main()
          {
           
局部变量定义
            <程序体>
          }
          sub1()
          {
           
局部变量定义
            <程序体>
          }
          sub2()
          {
           
局部变量定义
            <程序体>
          }
               .
               .
               .
          subN()
          {
           
局部变量定义
            <程序体>
          }
   
其中sub1(), ..., subN()代表用户定义的子函数, 程序体指Turbo C 2.0
提供的任何库函数调用语句、控制流程语句或其它用子函数调用语句等。
第三章          数据类型
    Turbo C语言中, 每个变量在使用之前必须定义其数据类型。Turbo C有以
下几种类型: 整型(int)、浮点型(float)、字符型(char)、指针型(*)、无值型
(void)以及结构(struct)和联合(union)。其中前五种是Turbo C的基本数据类型、
后两种数据类型(结构和联合)将在第五章介绍。
               整型(int)
1.                    整型数说明
加上不同的修饰符, 整型数有以下几种类型;
    signed short int     有符号短整型数说明。简写为short或int, 字长为2
                         字节共16位二进制数, 数的范围是-32768~32767。
    signed long int      有符号长整型数说明。简写为long, 字长为4字节共
                         32位二进制数, 数的范围是-2147483648~2147483647。
    unsigned short int   无符号短整型数说明。简写为unsigned int, 字长
                         为2字节共16位二进制数, 数的范围是0~65535。
    unsigned long int    无符号长整型数说明。简写为unsigned long, 字长
                         为4字节共32位二进制数, 数的范围是0~4294967295。
2.                    整型变量定义
可以用下列语句定义整型变量
    int a, b;            /*a、b被定义为有符号短整型变量,默认情形下是有符号变量*/
    unsigned long c;     /*c被定义为无符号长整型变量*/
int a=10;              /*变量a的初始化*/
int a;               /*变量a的声明或定义*/
3.                    整型常数表示
按不同的进制区分, 整型常数有三种表示方法:
    十进制数: 以非0开始的数
               如:220, -560, 45900
    八进制数: 以0开始的数
               如:06; 0106, 05788
    十六进制数:以0X或0x开始的数
               如:0X0D, 0XFF, 0x4e
一般来说,八进制和十六进制没有正负数之分.
    另外, 可在整型常数后添加一个"L"或"l"字母表示该数为长整型数, 如22L,
0773L, 0Xae4l。
               浮点型(float)
1.                    浮点数说明
    Turbo C中有以下两种类型的浮点数:
    float      单浮点数。字长为4 个字节共32 位二进制数,   数的范围是
               3.4x10-38E~3.4x10+38E
    double     双浮点数。字长为 8个字节共 64 位二进制数, 数的范围是
               1.7x10-308E~1.7x10+308E
    说明:
    浮点数均为有符号浮点数, 没有无符号浮点数。
2.                    浮点型变量定义
    可以用下列语句定义浮点型变量:
    float a, f;     /*a, f被定义为单浮点型变量*/
    double b;       /*b被定义为双浮点型变量*/
3.                    浮点常数表示
例如: +29.56, -56.33, -6.8e-18, 6.365
    说明:
    1. 浮点常数只有一种进制(十进制)。
    2. 所有浮点常数都被默认为double。
    3. 绝对值小于1的浮点数, 其小数点前面的零可以省略。如:0.22可写为.22,
-0.0015E-3可写为-.0015E-3。
    4. Turbo C默认格式输出浮点数时, 最多只保留小数点后六位。
               字符型(char)
    加上不同的修饰符, 可以定义有符号和无符号两种类型的字符型变量, 例如:
    char a:              /*a被定义为有符号字符变量*/
    unsigned char l;     /*l被定义为无符号字符变量*/
    字符在计算机中以其ASCII码方式表示, 其长度为1个字节, 有符号字符型数取值范围为-128~127, 无符号字符型数到值范围是0~255。因此在Turbo C语言中,字符型数据在操作时将按整型数处理, 如果某个变量定义成char, 则表明该变量是有符号的, 即它将转换成有符号的整型数。
    Turbo C中规定对ASCII码值大于0x80的字符将被认为是负数。例如ASCII 值
为0x8c的字符, 定义成char时,   被转换成十六进制的整数0xff8c 。 这是因当
ASCII码值大于0x80时, 该字节的最高位为1, 计算机会认为该数为负数,   对于
0x8c表示的数实际上是-74(8c的各位取反再加1), 而-74 转换成两字节整型数并
在计算机中表示时就是0xff8c( 对0074 各位取反再加1) 。 因此只有定义为
unsigned char 0x8c转换成整型数时才是8c。这一点在处理大于0x80的ASCII码
字符时(例如汉字码)要特别注意。一般汉字均定义为unsigned char。
    另外, 也可以定义一个字符型数组(关于数组后面再作详细介绍), 此时该数组表示一个字符串。
    例如:
        char str[10];
   
计算机在编译时, 将留出连续10个字符的空间, 即str[0]到str[9]共10个变
量, 但只有前9个供用户使用。第10个str[9]用来存放字符串终止符NULL即"/0",
但终止符是编编译程序自动加上的, 这一点应特别注意。
1.                    字符常数表示
    能用符号表示的字符可直接用单引号括起来表示, 如'a', '9', 'Z', 也可用
该字符的ASCII码值表示, 例如十进制数85表示大写字母'U', 十六进制数0x5d表示
']', 八进制数0102表示大写字母'B'。
    一些不能用符号表示的控制符, 只能用ASCII码值来表示, 如十进制数10 表示
换行, 下六进制数0x0d表示回车, 八进制数033表示Esc。Turbo C2.0中也有另外一
种表示表示方法, 如'/033'表示Esc, 这里'/ 0' 符号后面的数字表示十六进制的
ASCII值当然这种表示方法也适用于可睦接用符号表示的字符。
    另外, Turbo C2.0中有些常用的字符用以下特殊规定来表示:
          规定符            等价于           含义
          '/f'               '/X0C'          换页
          '/r'               '/X0D'          回车
          '/t'               '/X09'          制表键
          '/n'               '/X0A'          换行
          '//'               '/X5C'          /
          '/''               '/X27'          '
          '/"'               '/X22'          "
    对于字符串常量, 一般用双引号括起来表示, 如"Hello Turbo C2.0"。
               指针型(*)
指针是一种特殊的数据类型, 在其它语言中一般没有。指针是指向变量的地址,
实质上指针就是存贮单元的地址。 根据所指的变量类型不同,   可以是整型指针
(int *)、浮点型指针(float *)、字符型指针(char *)、结构指针(struct *)和联
合指针(union *)(结构指针和联合指针将在第4节中介绍)。
               无值型(void)
无值型字节长度为0, 主要有两个用途: 一是明确地表示一个函数不返回任何
值; 一是产生一个同一类型指针(可根据需要动态分配给其内存)。
    例如:
             void *buffer;    /*buffer被定义为无值型指针*/
               关键字和标识符 (keyword)
1.                    关键字
所谓关键字就是已被Turbo C2.0本身使用, 不能作其它用途使用的字。例如关键字不能
用作变量名、函数名等。
Turbo C2.0有以下关键字:
Turbo C2.0扩展的共11个
     asm       _cs       _ds       _es       _ss       cdecl
     far       near      huge      interrupt pascal
ANSI标准定义的共32个
     auto      double    int       struct    break     else
     long      switch    case      enum      register typedef
     char      extern    return    union     const     float
     short     unsigned continue for       signed    void
     default   goto      sizeof    volatile do        if
     while     static
2.                    标识符
所谓标识符是指常量、变量、语句标号以及用户自定义函数的名称。Turbo C 2.0
标识符的定义十分灵活。作为标识符必须满足以下规则:
1. 所有标识符必须由一个字母(a~z, A~Z)或下划线(_)开头;
2. 标识符的其它部分可以用字母、下划线或数字(0~9)组成;
3. 大小写字母表示不同意义, 即代表不同的标识符;
4. 一般来说,标识符只有前32个字符有效;
5. 标识符不能使用Turbo C2.0的关键字。
第四章           变量
               变量说明
    Turbo C2.0规定所有变量在使用前都必须中以说明。一条变量说明语句由数据
类型和其后的一个或多个变量名组成。变量说明的形式如下:
    类型 <变量表>;
    这里类型是指Turbo C2.0的有效数据类型。变量表是一个或多个标识符名, 每
个标识符之间用","分隔。
    例如:
          int i, j, k;   unsigned char c, str[5], *p;
               变量种类
    变量可以在程序中三个地方说明: 函数内部、函数的参数定义中或所有的函数
外部。根据所定义位置的不同, 变量可分为局部变量、形式参数和全程变量。
1.                        局部变量
    局部变量是指在函数内部说明的变量(有时也称为自动变量)。用关键字auto进
行说明, 当auto省略时, 所有的非全程变量都被认为是局部变量, 所以auto实际上
从来不用。
    局部变量在函数调用时自动产生, 但不会自动初始化, 随函数调用的结束, 这
个变量也就自动消失了, 下次调用此函数时再自动产生, 还要再赋值, 退出时又自
动消失。
 
2.                       形式参数
    形式参数是指在函数名后面的小括号里定义的变量, 用于接受来自调用函数的
参数。形式参数在函数内部可以象其它局部变量那样来作用。
    例如:
     puthz(int x, int y, int color, char *p)
     {
          int i, j, k;   /*定义局部变量*/
          <程序体>
     }
    其中x, y, color, *p为函数的形式参数, 不需要再进行说明就可在该函数内
直使用。
3.                    全程变量
    全程变量是指在所有函数之外说明的变量, 它在整个程序内部者是"可见的",
可以被任何一个函数使用, 并且在整个程序的运行中都保留其值。全程变量只要满
足在使用它以前和函数以外这两个条件, 可在程序的任何位置进行说明, 习惯上通
常在程序的主函数前说明。
    例如:
     #include<stdio.h>
     int test;                /*定义全程变量*/
     void f1(int x, float y); /*子函数说明*/
     void f2(void);           /*子函数说明*/
     main()
     {
          test=5;             /*给全程变量赋值*/
          f1(20, 5.5);        /*调用有形式参数的子函数f1()*/
                              /*test的值变成115*/
          f2();               /*调用f2(), test的值变为1150*/
     }
     void f1(int x, float y)
     {
          float z;            /*z定义为局部变量*/
          z=x*y;              /*计算*/
          test=test+z;
     }
     void f2(void)
     {
          int count=10;       /*定义局部变量并初始化*/
          test=test*count;
     }
 
    由于全程变量可被整个程序内的任何一个函数使用, 所以可作为函数之间传递
参数的手段, 但全程变量太多时, 内存开销变大。
 
               变量存储类型
 
    Turbo C2.0支持四种变量存储类型。说明符如下:
     auto      static    extern    register
下面分别来介绍。
1.                        auto
    auto称为自动变量, 已在前面作了介绍, 这里不再重复。
2.                       static
    static称为静态变量。根据变量的类型可以分为静态局部变量和静态全程变量。
    1. 静态局部变量
    它与局部变量的区别在于: 在函数退出时, 这个变量始终存在, 但不能被其它
函数使用, 当再次进入该函数时, 将保存上次的结果。其它与局部变量一样。
    2. 静态全程变量
    Turbo C2.0允许将大型程序分成若干独立模块文件分别编译, 然后将所有模块
的目标文件连接在一起, 从而提高编译速度, 同时也便于软件的管理和维护。静态
全程变量就是指只在定义它的源文件中可见而在其它源文件中不可见的变量。它与
全程变量的区别是: 全程变量可以再说明为外部变量(extern), 被其它源文件使用,
而静态全程变量却不能再被说明为外部的, 即只能被所在的源文件使用。
3.                        extern
    extern称为外部变量。为了使变量除了在定义它的源文件中可以使用外, 还要
被其它文件使用。因此,   必须将全程变量通知每一个程序模块文件,   此时可用
extern来说明。
    例如:
        文件1为file1.c                  文件2为file2.c
    int i, j;/*定义全程变量*/        extern int i, j;/*说明将i, j从
                                                     文件1中复制过来*/
    char c;                          extern char c; /*c复制过来*/
    void func1(int k);               func2()        /*用户定义函数*/
                                     {
    main()                              static float k;/*定义静态变量*/
    {                                   i=j*5/100;
          func1(20);/*调用函数*/        k=i/1.5;
          func2();                           .
          .                                  .
          .                                  .
          .                            }
     }
     func1(int k) /*用户定义函数*/
     {
          j=k*100;
     }
 
    对于以上两个文件file1.c和file2.c, 用Turbo C2.0的集成开发环境进行编译
连接时, 首先应建立一个.prj的文件。例如file.prj, 该文件内容如下:
     file1.c
     file2.c
    然后将file.prj的文件名写入主菜单Project中的Project Name项中。 再用F9
编译连接, 就可产生一个文件名为fioe.exe的可执行文件。
    外部变量和FORTRAN语言中的COMMOM定义的公共变量一样。
4.                        register
    register称为寄存器变量。它只能用于整型和字符型变量。定义符register说
明的变量被Turbo C2.0存储在CPU的寄存器中, 而不是象普通的变量那样存储在内
存中, 这样可以提高运算速度。但是Turbo C2.0只允许同时定义两个寄存器变量,
一旦超过两个, 编译程序会自动地将超过限制数目的寄存器变量当作非寄存器变量
来处理。因此, 寄存器变量常用在同一变量名频繁出现的地方。
    另外, 寄存器变量只适用于局部变量和函数的形式参数, 它属于auto型变量,
因此, 不能用作全程变量。定义一个整型寄存器变量可写成:
      register int a;
    对于以上所介绍的变量类型和变量存储类型将会在以后的学习中, 通过例行程
序中的定义、使用来逐渐加深理解。
 
5.                    数组变量
    所谓数组就是指具有相同数据类型的变量集, 并拥有共同的名字。数组中的每
个特定元素都使用下标来访问。数组由一段连续的存贮地址构成, 最低的地址对应
于第一个数组元素, 最高的地址对应最后一个数组元素。数组可以是一维的、也可
以是多维的。Turbo C2.0象它高级语方一样也使用数组变量。
 
    )一维数组
    一维数组的说明格式是:
      类型 变量名[长度];
    类型是指数据类型, 即每一个数组元素的数据类型, 包括整数型、浮点型、字
符型、指针型以及结构和联合。
    例如:
     int a[10];
     unsigned long a[20];
     char *s[5];
     char *f[];
 
    说明:
    1. 数组都是以0作为第一个元素的下标, 因此, 当说明一个int a[16] 的整型
数组时, 表明该数组有16个元素, a[0]~a[15], 一个元素为一个整型变量。
    2. 大多数字符串用一维数组表示。数组元素的多少表示字符串长度, 数组名
表示字符串中第一个字符的地址,   例如在语句char str[ 8] 说明的数组中存入
"hello"字符串后, str表示第一个字母"h"所在的内存单元地址。str[0] 存放的是
字母"h"的ASCII码值, 以此类推, str[4]存入的是字母"o"的ASCII码值, str[5]则
应存放字符串终止符'/0'。
    3. Turbo C2.0对数组不作边界检查。例如用下面语句说明两个数组
    char str1[5], str2[6];
    当赋给str1一个字符串"ABCDEFG"时, 只有"ABCDE"被赋给, "E" 将会自动的赋
str2, 这点应特别注意。
 
    )多维数组
    多维数组的一般说明格式是:
       类型 数组名[第n维长度][第n-1维长度]......[第1维长度];
    这种说明方式与BASIC、FORTRAN等语言中多维数组的说明不一样。
    例如:
      int m[3][2];       /*定义一个整数型的二维数组*/
      char c[2][2][3];   /*定义一个字符型的三维数组*/
    数组m[3][2]共有3*2=6个元素, 顺序为:
      m[0][0], m[0][1], m[1][0], m[1][1], m[2][0], m[2][1];
    数组c[2][2][3]共有2*2*3=12个元素, 顺序为:
      c[0][0][0], c[0][0][1], c[0][0][2],
      c[0][1][0], c[0][1][1], c[0][1][2],
      c[1][0][0], c[1][0][1], c[1][0][2],
      c[1][1][0], c[1][1][1], c[1][1][2],
    数组占用的内存空间(即字节数)的计算式为:
     字节数=第1维长度*第2维长度*...*第n维长度*该数组数据类型占用的字节数
 
               变量的初始化和赋值
 
1.                        变量的初始化
    变量的初始化是指变量在被说明的同时赋给一个初值。Turbo C2.0中外部变量
和静态全程变量在程序开始处被初始化, 局部变量包括静态局部变量是在进入定义
它们的函数或复合语句时才作初始化。所有全程变量在没有明确的初始化时将被自
动清零, 而局部变量和寄存器变量在未赋值前其值是不确定的。
    对于外部变量和静态变量, 初值必须是常数表达式, 而自动变量和寄存器变量
可以是任意的表达式, 这个表达式可以包括常数和前面说明过的变量和函数。
    1. 单个变量的初始化
    例如:
     float f0, f1=0.2;/*定义全程变量, 在初始化时f0被清零, f1被赋0.2*/
     main()
     {
          static int i=10, j; /*定义静态局部变量, 初始化时i被赋10, j不确
                              */
          int k=i*5;          /*定义局部变量, 初始化时k被赋10*5=50*/
          char c='y';         /*定义字符型指什变量并初始化*/
          .
          .
          .
     }
 
    2. 数组变量的初始化
    例如:
     main()
     {
          int p[2][3]={{2, -9, 0}, {8, 2, -5}}; /*定义数组p并初始化/*
          int m[2][4]={{27, -5, 19, 3}, {1, 8, -14, -2}};/*定义数组m并初
                                                         始化*/
          char *f[]={'A', 'B', 'C'};         /*定义数组f并初始化*/
          .
          .
          .
     }
    从上例可以看出: Turbo C2.0中数组进行初始化有下述规则:
    (1) 数组的每一行初始化赋值用"{}"并用","分开, 总的再加一对"{}"括起来,
最后以";"表示结束。
    (2) 多维数组的存储是按最右维数的变量变化最快的原则。
    (3) 多维数组存储是连续的, 因此可以用一维数组初始化的办法来初始化多维
数组。
    例如:
     int x[2][3]={1, 2, 3, 4, 5, 6};/*用一维数组来初始化二维数组*/
    (4) 对数组初始化时, 如果初值表中的数据个数比数组元素少, 则不足的数组
元素用0来填补。
    (5) 对指针型变量数组可以不规定维数, 在初始化赋值时, 数组维数从0 开始
被连续赋值。
    例如:
     char *f[]={'a', 'b', 'c'};
    初始化时将会给3个字符指针赋值, 即: *f[0]='a', *f[1]='b', *f[2]='c'。
 
    3. 指针型变量的初始化
    例如:
     main()
     {
          int *i=7899;        /*定义整型数指针变量并初始化*/
          float *f=3.1415926; /*定义浮点数指针变量并初始化*/
          char *s="Good";     /*定义字符型指针变量并初始化*/
          .
          .
          .
     }
2.                    变量的赋值
    变量赋值是给已说明的变量赋给一个特定值。
    1. 单个变量的赋值
    (1) 整型变量和浮点变量
    这两种变量采用下列格式赋值
          变量名=表达式;
    例如:
     main()
     {
          int a, m;      /*定义局部整型变量a, m*/
          float n;       /*定义局部浮点变量f*/
          a=100, m=20;   /*给变量赋值*/
          n=a*m*0.1;
          .
          .
          .
     }
 
    说明:
    Turbo C2.0中允许给多个变量赋同一值时可用连等的方式。
    例如:
     main()
     {
          int a, b, c;
          a=b=c=0;       /*同时给a,b,c赋值*/
          .
          .
          .
     }
 
    (2) 字符型变量
    字符型变量可以用三种方法赋值。
    例如:
     main()
     {
          char a0, a1, a2;    /*定义局部字符型变量a0, a1, a2*/
          a0='b';             /*将字母b赋给a0*/
          a1=50;              /*将数字2(十进制ASCII值为50赋给a1*/
          a2='/x0d';          /*将回车符赋给a2*/
          .
          .
          .
     }
 
    (3) 指针型变量
    例如:
     main()
     {
          int *i;
          char *str;
          *i=100;
          str="Good";
          .
          .
          .
     }
    *i表示i是一个指向整型数的指针, 即*i是一个整型变量, i是一个指向该整型
变量的地址。
    *str表示str是一个字符型指针, 即保留某个字符地址。在初始化时, str没有
什么特殊的值, 而在执行str="Good"时, 编译器先在目标文件的某处保留一个空间
存放"Good/0"的字符串, 然后把这个字符串的第一个字母"G"的地址赋给str, 其中
字符串结尾符"/0"是编译程序自动加上的。
    对于指针变量的使用要特别注意。上例中两个指针在说明前没有初始化, 因此
这两指针为随机地址, 在小存储模式下使用将会有破坏机器的危险。正确的使用办
法如下:
    例如:
     main()
     {
          int *i;
          char *str;
          i=(int*)malloc(sizeof(int));
          i=420;
          str=(char*)malloc(20);
          str="Good, Answer!";
          .
          .
          .
     }
    上例中, 函数(int*)malloc(sizeof(int))表示分配连续的sizeof(int)=2个字
节的整型数存储空间并返回其首地址。同样(char*)malloc(20)表示分配连续20 个
字节的字符存储空间并返回首地址(有关该函数以后再详述)。由动态内存分配函数
malloc()分配了内存空间后, 这部分内存将专供指针变量使用。
    如果要使i指向三个整型数, 则用下述方法。
    例如:
     #include<alloc.h>
     main()
     {
          int *a;
          a=(int*)malloc(3*sizeof(int));
          *a=1234;
          *(a+1)=4567;
          *(a+2)=234;
          .
          .
          .
     }
    *i=1234表示把1234存放到i指向的地址中去, 但对于*(i+1)=4567, 如果认为
4567存放到i指向的下一个字节中就错了。Turbo C2.0中只要说明i为整型指针,
    (i+1) 等价于   i+1*sizeof(int)
同样 (i+2) 等价于   i+2*sizeof(int)
 
    2. 数组变量的赋值
    (1) 整型数组和浮点数组的赋值
    例如:
     main()
     {
          int m[2][2];
          float n[3];
          m[0][0]=0, m[0][1]=17, m[1][0]=21;/*数组元素赋值*/
          n[0]=109.5, n[1]=-8.29, n[2]=0.7;
          .
          .
          .
     }
 
    (2)字符串数组的赋值
    例如:
      main()
     {
          char s[30];
          strcpy(s, "Good News!"); /*给数组赋字符串*/
          .
          .
          .
     }
    上面程序在编译时, 遇到char s[30]这条语句时, 编译程序会在内存的某处留
出连续30个字节的区域, 并将第一个字节的地址赋给s。当遇到strcpy( strcpy 为
Turbo C2.0的函数)时, 首先在目标文件的某处建立一个"Good News!/0" 的字符串。
其中/0表示字符串终止, 终止符是编译时自动加上的, 然后一个字符一个字符地复
制到s所指的内存区域。因此定义字符串数组时, 其元素个数至少应该比字符串的
长度多1。
    注意:
    1. 字符串数组不能用"="直接赋值, 即s="Good News!"是不合法的。所以应分
清字符串数组和字符串指针的不同赋值方法。
    2. 对于长字符串, Turbo C2.0允许使用下述方法:
    例如:
     main()
     {
          char s[100];
          strcpy(s, "The writer would like to thank you for"
                    "your interest in his book. He hopes you"
                    "can get some helps from the book.");
          .
          .
          .
     }
 
    (3)指针数组赋值
    例如:
     main()
     {
          char *f[2];
          int *a[2];
          f[0]="thank you";   /*给字符型数组指针变量赋值*/
          f[1]="Good Morning";
          *a[0]=1, *a[1]=-11; /*给整型数数组指针变量赋值*/
          .
          .
          .
     }
 
3.                    数组与指针
    数组与指针有密切的联系。数组名本身就是该数组的指针, 反过来, 也可以把
指针看成一个数组, 数组名和指针实质上都是地址, 但是指针是变量, 可以作运算。
而数组名是常量, 不能进行运算。
    例如:
     main()
     {
          char s[30], *p; /*定义字符型数组和指针变量*/
          p=s;            /*指针p指向数组s的第一个元素s[0]的地址*/
          .
          .
          .
          *(p+8);         /*指针p指向数组s的第9个元素s[8]的地址*/
          .
          .
          .
     }
    由上例可以看出数组和指针有如下关系:
    (p+i)=&(s[i])
    *(p+i)=s[i]
    因此, 利用上述表达式可以对数组和指针进行互换。两者的区别仅在于: 数组
s是程序自动为它分配了所需的存储空间; 而指针p则是利用动态分想函数为它分配
存储空间或赋给它一个已分配的空间地址。
 
第五章          运算符
 
    Turbo C的运算符非常丰富, 主要分为三大类: 算术运算符, 关系运算符与
逻辑运算符, 按位运算符。除此之外, 还有一些用于完成特殊任务的运算符。下
面分别进行介绍。
 
               算术运算符
    Turbo C的算术运算符如下:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
       操作符                          作用
────────────────────────────
          +                        , 一目取正
          -                        , 一目取负
          *                            
          /                            
          %                            取模
          --                            1
          ++                            1
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1.                    一目和二目操作
    一目操作是指对一个操作数进行操作。例如: -a是对a进行一目负操作。
    二目操作(或多目操作)是指两个操作数(或多个操作数)进行操作。
    Turbo C中加、减、乘、除、取模的运算与其它高级语言相同。需要注意
的是除法和取模运算。
    例如:
      15/2    15除以2商的整数部分7
      15%2    15除以2的余数部分1
    对于取模运算符"%", 不能用于浮点数。
    另外, 由于Turbo C中字符型数会自动地转换成整型数, 因此字符型数也可
以参加二目运算。
    例如:
     main()
     {
          char m, n;     /*定义字符型变量*/
          m='c';         /*m赋小写字母'c'*/
          n=m+'A'-'a';   /*c中的小写字母变成大写字母'B'后赋给n*/
          ...
     }
    上例中m='c'即m=98, 由于字母A和a的ASCII码值分别为65和97。这样可以将
小写字母变成大写字母, 反之, 如果要将大写字母变成小写字母, 则用c+ 'a'
-'A'进行计算。
 
2.                    增量运算
    Turbo C中有两个很有用的运算符, 在其它高级语言中通常没有。这两个
运算符就是增1和减1运算符"++"和"--", 运算符"++"是操作数加1, 而"--" 则是
操作数减1。
    例如:
      x=x+1         可写成x++, 或++x
      x=x-1         可写成x--, 或--x
    x++(x--)++x(--x)在上例中没有什么区别, 但x=m++和x=++m却有很大差别。
      x=m++    表示将m的值赋给x后, m加1。
      x=++m    表示m先加1后, 再将新值赋给x。
3.                    赋值语句中的数据类型转换
    类型转换是指不同类型的变量混用时的类型改变。
    在赋值语句中, 类型转换规则是:
     等号右边的值转换为等号左边变量所属的类型。
    例如:
     main()
     {
          int i, j;      /*定义整型变量*/
          float f, g=2.58;    /*定义浮点型变量*/
          f=i*j;         /*ij的乘积是整型数, 被转换成为浮点数赋给f*/
          i=g;           /*g中的浮点型数转换成为整型数赋给i*/
          ...
    }
    由于Turbo C按上述数据类型转换规则, 因此在作除法运算时应特别注意。
    例如:
     main()
     {
          float f;
          int i=15;
          f=i/2;
     }
    上面程序经运行后, f=7并不等于准确值7.5。正确的程序应该是:
     main()
     {
          float f;
          int i=15;
          f=i/2.0;
     }
    也可直接将i定义为浮点数。
               关系运算符和逻辑运算符
1.                       逻辑运算符
    逻辑运算符是指用形式逻辑原则来建立数值间关系的符号。
    Turbo C的逻辑运算符如下:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        操作符                      作用
─────────────────────────────
          &&                       逻辑与
         ||                       逻辑或
          !                        逻辑非
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
2.                    关系运算符
    关系运算符是比较两个操作数大小的符号。
    Turbo C的关系运算符如下:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        操作符                        作用
─────────────────────────────
          >                           大于
          >=                        大于等于
          <                           小于
          <=                        小于等于
          ==                          等于
          !=                         不等于
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    关系运算符和逻辑运算符的关键是真(true)和假(false)的概念。Turbo C中
true可以是不为0的任何值, 而false则为0。 使用关系运算符和逻辑运算符表达
式时, 若表达式为真(即true)则返回1, 否则, 表达式为假(即false), 则返回0。
    例如:
     100>99         返回1
     10>(2+10)      返回0
     !1&&0          返加0
    对上例中表达式!1&&0, 先求!1和先求1&&0将会等于出不同的结果, 那么何
者优先呢? 这在Turbo C中是有规定的。 有关运算符的优先级本节后面将会讲到。
 
3.                    按位运算符
    Turbo C和其它高级语言不同的是它完全支持按位运算符。这与汇编语言的
位操作有些相似。
    Turbo C中按位运算符有:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        操作符                       作用
────────────────────────────
          &                        位逻辑与
          |                        位逻辑或
          ^                       位逻辑异或
          -                        位逻辑反
          >>                         右移
          <<                         左移
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    按位运算是对字节或字中的实际位进行检测、设置或移位, 它只适用于字符
型和整数型变量以及它们的变体, 对其它数据类型不适用。
    关系运算和逻辑运算表达式的结果只能是1或0。 而按位运算的结果可以取0
1以外的值。
    要注意区别按位运算符和逻辑运算符的不同, 例如, 若x=7, 则x&&8 的值为
(两个非零值相与仍为非零), 而x&8的值为0。
    移位运算符">>"和"<<"是指将变量中的每一位向右或向左移动, 其通常形式
:
     右移:     变量名>>移位的位数
     左移:     变量名<<移位的位数
    经过移位后, 一端的位被"挤掉",   而另一端空出的位以0 填补,   所以,
Turbo C中的移位不是循环移动的。
 
4.                    Turbo C的特殊运算符
)"?"运算符
    "?"运算符是一个三目运算符, 其一般形式是:
      <表达式1>?<表达式2>:<表达式3>;
    "?"运算符的含义是: 先求表达式1的值, 如果为真, 则求表达式2 的值并把
它作为整个表达式的值; 如果表达式1 的值为假, 则求表达式3 的值并把它作为
整个表达式的值。
    例如:
     main()
     {
          int x, y;
          x=50;
          y=x>70?100:0;
     }
    本例中, y将被赋值0。如果x=80, y将被赋值100。
    因此, "?"运算符可以代替某些if-then-else形式的语句。
 
)"&"和"*"运算符
    "&"运算符是一个返回操作数地址的单目操作符。
    "*"运算符是对"&"运算符的一个补充, 它返回位于这个地址内的变量值, 也
是单目操作符。
    例如:
     main()
     {
          int i, j, *m;
          i=10;
          m=&i;          /*将变量i的地址赋给m*/
          j=*m;          /*地址m所指的单元的值赋给j*/
     }
    上面程序运行后, i=10, m为其对应的内存地址, j的值也为10。
 
)","运算符
    ","运算符用于将多个表达式串在一起, ","运算符的左边总不返回, 右边表
达式的值才是整个表达式的值。
    例如:
     main()
     {
          int x, y;
          x=50;
          y=(x=x-5, x/5);
     }
    上面程序执行后y值为9, 因为x的初始值为50, 减5后变为45, 45除5为9赋给
y。
 
 
)sizeof运算符
    sizeof运算符是一个单目运算符, 它返回变量或类型的字节长度。
    例如:
     sizeof(double) 8
     sizeof(int)    2
    也可以求已定义的变量, 例如:
     float f;
     int i;
     i=sizeof(f);
    i的值将为4。
)联合操作
    Turbo C中有一特殊的简写方式, 它用来简化一种赋值语句, 适用于所有的
双目运算符。其一般形式为:
     <变量>=<变量><操作数><表达式>
    相当于
     <变量><操作数>=<表达式>
    例如:
      a=a+b         可写成    a+=b
      a=a&b         可写成    a&=b
      a=a/(b-c)     可写成    a/=b-c
               Turbo C运算符的优先级
    Turbo C规定了运算符的优先次序即优先级。 当一个表达式中有多个运算符
参加运算时, 将按下表所规定的优先级进行运算。表中优先级从上往下逐渐降低,
同一行优先级相同。
    例如:
       表达式 10>4&&!(100<99)||3<=5 的值为1
       表达式 10>4&&!(100<99)&&3<=5 的值为0
 
               Turbo C运算符的优先次序
━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━
                    表达式                              ┃优先级
────────────────────────────╂────
 ()(小括号) [](数组下标) .(结构成员) ->(指针型结构成员)┃ 最高
────────────────────────────┃ ↑
 !(逻辑非) .(位取反) -(负号) ++(加1) --(减1) &(变量地址)┃ │
────────────────────────────┃ │
   *(指针所指内容) type(函数说明) sizeof(长度计算)    ┃ │
────────────────────────────┃ │
     *()     /(除)     %(取模)                        ┃ │
────────────────────────────┃ │
     +()     -(减)                                    ┃ │
────────────────────────────┃ │
     <<(位左移)          >>(位右移)                     ┃ │
────────────────────────────┃ │
     <(小于)   <=(小于等于)   >(大于)   >=(大于等于)    ┃ │
────────────────────────────┃ │
     ==(等于)       !=(不等于)                          ┃ │
────────────────────────────┃ │
     &(位与)                                            ┃ │
────────────────────────────┃ │
     ^(位异或)                                          ┃ │
────────────────────────────┃ │
     |(位或)                                            ┃ │
────────────────────────────┃ │
     &&(逻辑与)                                         ┃ │
────────────────────────────┃ │
     ||(逻辑或)                                         ┃ │
────────────────────────────┃ │
     ?:(?表达式)                                        ┃ │
────────────────────────────┃ │
     =    +=   -=(联合操作)                             ┃ │
────────────────────────────┃ │
     ,(逗号运算符)                                      ┃ 最低
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
第六章          输入输出函数及控制流程语句
    本节主要介绍Turbo C2.0标准输入输出函数和文件的输入输出函数。通过本
节的学习可以使读者掌握Turbo C2.0的屏幕输出、键盘输入输出以及磁盘文件的
读写函数, 并能开始进行一些简单的程序的编写。
    控制流程语句主要包括: 条件语句、循环语句和开关语句。
 
 
 
                  标准输入输出函数
 
1.                    格式化输入输出函数
    Turbo C2.0 标准库提供了两个控制台格式化输入、 输出函数printf( ) 和
scanf(), 这两个函数可以在标准输入输出设备上以各种不同的格式读写数据。
printf()函数用来向标准输出设备(屏幕)写数据; scanf() 函数用来从标准输入
设备(键盘)上读数据。下面详细介绍这两个函数的用法。
    一、printf()函数
    printf()函数是格式化输出函数, 一般用于向标准输出设备按规定格式输出
信息。在编写程序时经常会用到此函数。printf()函数的调用格式为:
      printf("<格式化字符串>", <参量表>);
    其中格式化字符串包括两部分内容: 一部分是正常字符, 这些字符将按原
样输出; 另一部分是格式化规定字符, 以"%"开始, 后跟一个或几个规定字符,
用来确定输出内容格式。
    参量表是需要输出的一系列参数, 其个数必须与格式化字符串所说明的输出
参数个数一样多, 各参数之间用","分开, 且顺序一一对应, 否则将会出现意想
不到的错误。
    1. 格式化规定符
    Turbo C2.0提供的格式化规定符如下:
━━━━━━━━━━━━━━━━━━━━━━━━━━
   符号                  作用
──────────────────────────
    %d              十进制有符号整数
    %u              十进制无符号整数
    %f              浮点数
    %s              字符串
    %c              单个字符
    %p              指针的值
    %e              指数形式的浮点数
    %x, %X          无符号以十六进制表示的整数
    %0              无符号以八进制表示的整数
    %g              自动选择合适的表示法
━━━━━━━━━━━━━━━━━━━━━━━━━━
    说明:
    (1). 可以在"%"和字母之间插进数字表示最大场宽。
     例如: %3d   表示输出3位整型数, 不够3位右对齐。
            %9.2f 表示输出场宽为9的浮点数, 其中小数位为2, 整数位为6,
                  小数点占一位, 不够9位右对齐。
            %8s   表示输出8个字符的字符串, 不够8个字符右对齐。
    如果字符串的长度、或整型数位数超过说明的场宽, 将按其实际长度输出。
但对浮点数, 若整数部分位数超过了说明的整数位宽度, 将按实际整数位输出;
若小数部分位数超过了说明的小数位宽度, 则按说明的宽度以四舍五入输出。
    另外, 若想在输出值前加一些0, 就应在场宽项前加个0。
    例如:   %04d 表示在输出一个小于4位的数值时, 将在前面补0使其总宽度
4位。
    如果用浮点数表示字符或整型量的输出格式, 小数点后的数字代表最大宽度,
小数点前的数字代表最小宽度。
    例如: %6.9s 表示显示一个长度不小于6且不大于9的字符串。若大于9, 则
9个字符以后的内容将被删除。
    (2). 可以在"%"和字母之间加小写字母l, 表示输出的是长型数。
    例如:   %ld   表示输出long整数
            %lf   表示输出double浮点数
    (3). 可以控制输出左对齐或右对齐, 即在"%"和字母之间加入一个"-" 号可
说明输出为左对齐, 否则为右对齐。
    例如:   %-7d 表示输出7位整数左对齐
            %-10s 表示输出10个字符左对齐
2.                     一些特殊规定字符
━━━━━━━━━━━━━━━━━━━━━━━━━━
    字符                           作用
──────────────────────────
     /n                   换行
     /f                   清屏并换页
     /r                   回车
     /t                   Tab
     /xhh                 表示一个ASCII码用16进表示,
                          其中hh是1到2个16进制数
━━━━━━━━━━━━━━━━━━━━━━━━━━
    由本节所学的printf()函数, 并结合上一节学习的数据类型, 编制下面的程
, 以加深对Turbo C2.0数据类型的了解。
    1
     #include<stdio.h>
     #include<string.h>
     int main()
     {
          char c, s[20], *p;
          int a=1234, *i;
          float f=3.141592653589;
          double x=0.12345678987654321;
          p="How do you do";
          strcpy(s, "Hello, Comrade");
          *i=12;
          c='/x41';
          printf("a=%d/n", a);     /*结果输出十进制整数a=1234*/
          printf("a=%6d/n", a);    /*结果输出6位十进制数a= 1234*/
          printf("a=%06d/n", a);   /*结果输出6位十进制数a=001234*/
          printf("a=%2d/n", a);    /*a超过2位, 按实际值输出a=1234*/
          printf("*i=%4d/n", *i); /*输出4位十进制整数*i= 12*/
          printf("*i=%-4d/n", *i); /*输出左对齐4位十进制整数*i=12*/
          printf("i=%p/n", i);     /*输出地址i=06E4*/
          printf("f=%f/n", f);     /*输出浮点数f=3.141593*/
          printf("f=6.4f/n", f);   /*输出6位其中小数点后4位的浮点数
                                      f=3.1416*/
          printf("x=%lf/n", x);    /*输出长浮点数x=0.123457*/
          printf("x=%18.16lf/n", x);/*输出18位其中小数点后16位的长浮点
                                      x=0.1234567898765432*/
          printf("c=%c/n", c);     /*输出字符c=A*/
          printf("c=%x/n", c);     /*输出字符的ASCII码值c=41*/
          printf("s[]=%s/n", s);   /*输出数组字符串s[]=Hello, Comrade*/
          printf("s[]=%6.9s/n", s);/*输出最多9个字符的字符串s[]=Hello,
                                     Co*/
          printf("s=%p/n", s);     /*输出数组字符串首字符地址s=FFBE*/
          printf("*p=%s/n", p);    /* 输出指针字符串p=How do you do*/
          printf("p=%p/n", p);     /*输出指针的值p=0194*/
          getch();
          retunr 0;
     }
    上面结果中的地址值在不同计算机上可能不同。
    1.中第一条语句#include<stdio.h>的含义是调用另一个文件stdio.h, 这
是一个头文件, 其中包括全部标准输入输出库函数的数据类型定义和函数说明。
Turbo C2.0对每个库函数便用的变量及函数类型都已作了定义与说明, 放在相应
头文件"*.h"中, 用户用到这些函数时必须要用#include<*.h>或#include"*. h"
语句调用相应的头文件, 以供连接。若没有用此语句说明, 则连接时将会出现错
误。
3.                    scanf()函数
    scanf()函数是格式化输入函数, 它从标准输入设备(键盘) 读取输入的信息。
其调用格式为:
      scanf("<格式化字符串>", <地址表>);
    格式化字符串包括以下三类不同的字符;
    1. 格式化说明符: 格式化说明符与printf()函数中的格式说明符基本相同。
    2. 空白字符: 空白字符会使scanf()函数在读操作中略去输入中的一个或多
个空白字符。
    3. 非空白字符: 一个非空白字符会使scanf()函数在读入时剔除掉与这个非
空白字符相同的字符。
    地址表是需要读入的所有变量的地址, 而不是变量本身。这与printf()函数
完全不同, 要特别注意。各个变量的地址之间同","分开。
    2:
     main()
     {
          int i, j;
          printf("i, j=?/n");
          scanf("%d, %d", &i, &j);
     }
 
    上例中的scanf()函数先读一个整型数, 然后把接着输入的逗号剔除掉, 最
后读入另一个整型数。如果","这一特定字符没有找到, scanf()函数就终止。若
参数之间的分隔符为空格, 则参数之间必须输入一个或多个空格。
    说明:
    (1). 对于字符串数组或字符串指针变量, 由于数组名和指针变量名本身就
是地址, 因此使用scanf()函数时, 不需要在它们前面加上"&"操作符。
    3
      mian()
     {
          char *p, str[20];
          scanf("%s", p);          /*从健盘输入字符串*/
          scanf("%s", str);
          printf("%s/n", p);       /*向屏幕输出字符串*/
          printf("%s/n", str);
     }
 
    (2). 可以在格式化字符串中的"%"各格式化规定符之间加入一个整数, 表示
任何读操作中的最大位数。
    如例3中若规定只能输入10字符给字符串指针p, 则第一条scanf() 函数语句
变为
          scanf("%10s", p);
    程序运行时一旦输入字符个数大于10, p就不再继续读入, 而后面的一个读
入函数即scanf("%s", str)就会从第11个字符开始读入。
    实际使用scanf()函数时存在一个问题, 下面举例进行说明:
    当使用多个scanf()函数连续给多个字符变量输入时, 例如:
     main()
     {
          char c1, c2;
          scanf("%c", &c1);
          scanf("%c", &c2);
          printf("c1 is %c, c2 is %c", c2/1, c2);
     }
 
    运行该程序, 输入一个字符A后回车 (要完成输入必须回车), 在执行scanf
("%c", &c1)时, 给变量c1赋值"A", 但回车符仍然留在缓冲区内, 执行输入语句
scanf("%c", &c2)时, 变量c2输出的是一空行, 如果输入AB后回车, 那么输出结
果为: c1 is A, c2 is B。
    要解决以上问题, 可以在输入函数前加入清除函数fflush()( 这个函数的使
用方法将在本节最后讲述)。修改以上程序变成:
     #include<stdio.h>
     main()
     {
          char c1, c2;
          scanf("%c", &c1);
          fflush(stdin);
          scanf("%c", &c2);
          printf("c1 is %c, c2 is %c", c1, c2);
     }
 
    1.1.2 非格式化输入输出函数
    非格式化输入输出函数可以由上面讲述的标准格式化输入输出函数代替, 但
这些函数编译后代码少, 相对占用内存也小, 从而提高了速度, 同时使用也比较
方便。下面分别进行介绍。
    一、puts()和gets()函数
    1. puts()函数
    puts()函数用来向标准输出设备(屏幕)写字符串并换行, 其调用格式为:
     puts(s);
    其中s为字符串变量(字符串数组名或字符串指针)。
    puts()函数的作用与语printf("%s/n", s)相同。
    4:
     main()
     {
          char s[20], *f;                 /*定义字符串数组和指针变量*/
          strcpy(s, "Hello! Turbo C2.0"); /*字符串数组变量赋值*/
          f="Thank you";                  /*字符串指针变量赋值*/
          puts(s);
          puts(f);
     }
 
    说明:
    (1). puts()函数只能输出字符串, 不能输出数值或进行格式变换。
    (2). 可以将字符串直接写入puts()函数中。如:
          puts("Hello, Turbo C2.0");
 
    2. gets()函数
    gets()函数用来从标准输入设备(键盘)读取字符串直到回车结束, 但回车符
不属于这个字符串。其调用格式为:
    gets(s);
    其中s为字符串变量(字符串数组名或字符串指针)。
    gets(s)函数与scanf("%s", &s)相似, 但不完全相同, 使用scanf("%s", &s)
函数输入字符串时存在一个问题, 就是如果输入了空格会认为输入字符串结束,
空格后的字符将作为下一个输入项处理, 但gets() 函数将接收输入的整个字符
串直到回车为止。
    5
     main()
     {
          char s[20], *f;
          printf("What's your name?/n");
          gets(s);                      /*等待输入字符串直到回车结束*/
          puts(s);                      /*将输入的字符串输出*/
          puts("How old are you?");
          gets(f);
          puts(f);
     }
    说明:
    (1). gets(s)函数中的变量s为一字符串。如果为单个字符, 编译连接不会
有错误, 但运行后会出现"Null pointer asignmemt"的错误。
 
    二、putchar()、getch()、getche()和getchar()函数
4.                         putchar()函数
    putchar()函数是向标准输出设备输出一个字符, 其调用格式为:
     putchar(ch);
    其中ch为一个字符变量或常量。
    putchar()函数的作用等同于printf("%c", ch);
    6:
     #include<stdio.h>
     main()
     {
          char c:             /*定义字符变量*/
          c='B';              /*给字符变量赋值*/
          putchar(c);         /*输出该字符*/
          putchar('/x42');    /*输出字母B*/
          putchar(0x42);      /*直接用ASCII码值输出字母B*/
     }
    从本例中的连续四个字符输出函数语句可以分清字符变量的不同赋值方法。
5.                      getch()、getche()和getchar()函数
    (1) getch()getche()函数
    这两个函数都是从键盘上读入一个字符。其调用格式为:
     getch();
     getche();
    两者的区别是: getch()函数不将读入的字符回显在显示屏幕上, 而getche()
函数却将读入的字符回显到显示屏幕上。
    7:
     #include<stdio.h>
     main()
     {
          char c, ch;
          c=getch();     /*从键盘上读入一个字符不回显送给字符变量c*/
          putchar(c);    /*输出该字符*/
          ch=getche();   /*从键盘上带回显的读入一个字符送给字符变量ch*/
          putchar(ch);
     }
    利用回显和不回显的特点, 这两个函数经常用于交互输入的过程中完成暂停
等功能。
    8:
     #include<stdio.h>
     main()
     {
          char c, s[20];
          printf("Name:");
          gets(s);
          printf("Press any key to confinue...");
          getch(); /*等待输入任一键*/
     }
 
    (2) getchar()函数
    getchar()函数也是从键盘上读入一个字符, 并带回显。它与前面两个函数
的区别在于: getchar()函数等待输入直到按回车才结束, 回车前的所有输入字
符都会逐个显示在屏幕上。但只有第一个字符作为函数的返回值。
    getchar()函数的调用格式为:
     getchar();
    9:
     #include<stdio.h>
     main()
     {
          char c;
          c=getchar();   /*从键盘读入字符直到回车结束*/
          putchar(c);    /*显示输入的第一个字符*/
          getch();       /*等待按任一健*/
     }
               文件的输入输出函数
    键盘、显示器、打印机、磁盘驱动器等逻辑设备, 其输入输出都可以通过文
件管理的方法来完成。而在编程时使用最多的要算是磁盘文件, 因此本节主要以
磁盘文件为主, 详细介绍Turbo C2.0提供的文件操作函数, 当然这些对文件的操
作函数也适合于非磁盘文件的情况。
    另外, Turbo C2.0提供了两类关于文件的函数。一类称做标准文件函数也称
缓冲型文件函数, 这是ANSI标准定义的函数; 另一类叫非标准文件函数, 也称非
缓冲型文件函数。这类函数最早公用于UNIX操作系统, 但现在MS-DOS3.0 以上版
本的操作系统也可以使用。下面分别进行介绍。
 
1.                    标准文件函数
    标准文件函数主要包括文件的打开、关闭、读和写等函数。不象BASIC 、
FORTRAN语方有顺序文件和随机文件之分,   在打开时就应按不同的方式确定。
Turbo C2.0并不区分这两种文件, 但提供了两组函数, 即顺序读写函数和随机读
写函数。
    一、文件的打开和关闭
    任何一个文件在使用之前和使用之后, 必须要进行打开和关闭, 这是因为操
作系统对于同时打开的文件数目是有限制的, DOS操作系统中,    可以在DEVICE
.SYS中定义允许同时打开的文件数n(用files=n定义)。其中n 为可同时打开的文
件数, 一般n<=20。因此在使用文件前应打开文件, 才可对其中的信息进行存取。
用完之后需要关闭, 否则将会出现一些意想不到的错误。Turbo C2.0提供了打开
和关闭文件的函数。
    1. fopen()函数
    fopen函数用于打开文件, 其调用格式为:
     FILE *fopen(char *filename, *type);
    在介绍这个函数之;前, 先了解一下下面的知识。
    (1) (stream)和文件(file)
    流和文件 在Turbo C2.0中是有区别的, Turbo C2.0 为编程者和被访问的设
备之间提供了一层抽象的东西, 称之为"流", 而将具体的实际设备叫做文件。
流是一个逻辑设备, 具有相同的行为。因此, 用来进行磁盘文件写的函数也同样
可以用来进行打印机的写入。在Turbo C2.0中有两种性质的流:   文字流( text
stream)和二进制(binary stream)。对磁盘来说就是文本文件和二进制文件。本
软件为了便于让读者易理解Turbo C2.0语言而没有对流和文件作特别区分。
    (2) 文件指针FILE
    实际上FILE是一个新的数据类型。它是Turbo C2.0的基本数据类型的集合,
称之为结构指针。有关结构的概念将在第四节中详细介绍, 这里只要将FILE理解
为一个包括了文件管理有关信息的数据结构, 即在打开文件时必须先定义一个文
件指针。
    (3) 以后介绍的函数调用格式将直接写出形式参数的数据类型和函数返回值
的数据类型。例如: 上面打开文件的函数, 返回一个文件指针, 其中形式参数有
两个, 均为字符型变量(字符串数组或字符串指针)。本软件不再对函数的调用格
式作详细说明。
    现在再来看打开文件函数的用法。
    fopen()函数中第一个形式参数表示文件名, 可以包含路径和文件名两部分。
:
     "B:TEST.DAT"
     "C://TC//TEST.DAT"
    如果将路径写成"C:/TC/TEST.DAT"是不正确的, 这一点要特别注意。
    第二个形式参数表示打开文件的类型。关于文件类型的规定参见下表。
                        文件操作类型
    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
          字符                含义
    ────────────────────────────
           "r"           打开文字文件只读
           "w"           创建文字文件只写
           "a"           增补, 如果文件不存在则创建一个
           "r+"          打开一个文字文件读/写
           "w+"          创建一个文字文件读/写
           "a+"          打开或创建一个文件增补
           "b"           二进制文件(可以和上面每一项合用)
           "t"           文这文件(默认项)
    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    如果要打开一个CCDOS子目录中, 文件名为CLIB的二进制文件, 可写成:
     fopen("c://ccdos//clib", "rb");
    如果成功的打开一个文件, fopen()函数返回文件指针,   否则返回空指针
(NULL)。由此可判断文件打开是否成功。
    2. fclose()函数
    fclose()函数用来关闭一个由fopen()函数打开的文件 , 其调用格式为:
      int fclose(FILE *stream);
    该函数返回一个整型数。当文件关闭成功时, 返回0, 否则返回一个非零值。
可以根据函数的返回值判断文件是否关闭成功。
    10:
     #iclude<stdio.h>
     main()
     {
          FILE *fp;                /*定义一个文件指针*/
          int i;
          fp=fopen("CLIB", "rb"); /*打开当前目录名为CLIB的文件只读*/
          if(fp==NULL)             /*判断文件是否打开成功*/
             puts("File open error");/*提示打开不成功*/
          i=fclose(fp);            /*关闭打开的文件*/
          if(i==0)                 /*判断文件是否关闭成功*/
            printf("O,K");         /*提示关闭成功*/
          else
            puts("File close error");/*提示关闭不成功*/
     }
 
2.                    有关文件操作的函数
    本节所讲的文件读写函数均是指顺序读写, 即读写了一条信息后, 指针自动
1。下面分别介绍写操作函数和读操作函数。
 
    1. 文件的顺序写函数
    fprintf()fputs()和fputc()函数
    函数fprintf()、fputs()和fputc()均为文件的顺序写操作函数, 其调用格
式如下:
    int fprintf(FILE *stream, char *format, <variable-list>);
    int fputs(char *string, FILE *steam);
    int fputc(int ch, FILE *steam);
    上述三个函数的返回值均为整型量。fprintf() 函数的返回值为实际写入文
件中的字罕个数(字节数)。如果写错误, 则返回一个负数, fputs()函数返回0时
表明将string指针所指的字符串写入文件中的操作成功, 返回非0时, 表明写操
作失败。fputc()函数返回一个向文件所写字符的值, 此时写操作成功, 否则返
EOF(文件结束结束其值为-1, 在stdio.h中定义)表示写操作错误。
     fprintf( ) 函数中格式化的规定与printf( ) 函数相同,   所不同的只是
fprintf()函数是向文件中写入。而printf()是向屏幕输出。
    下面介绍一个例子, 运行后产后一个test.dat的文件。
    11:
     #include<stdio.h>
     main()
     {
          char *s="That's good news"); /*定义字符串指针并初始化*/
          int i=617;                    /*定义整型变量并初始化*/
          FILE *fp;                     /*定义文件指针*/
          fp=fopne("test.dat", "w");    /*建立一个文字文件只写*/
          fputs("Your score of TOEFLis", fp);/*向所建文件写入一串字符*/
          fputc(':', fp);               /*向所建文件写冒号:*/
          fprintf(fp, "%d/n", i);       /*向所建文件写一整型数*/
          fprintf(fp, "%s", s);         /*向所建文件写一字符串*/
          fclose(fp);                   /*关闭文件*/
     }
    DOS的TYPE命令显示TEST.DAT的内容如下所示:
    屏幕显示
      Your score of TOEFL is: 617
      That's good news
 
    2. 文件的顺序读操作函数
    fscanf()fgets()和fgetc()函数
    函数fscanf()、fgets()和fgetc()均为文件的顺序读操作函数, 其调用格式
如下:
     int fscanf(FILE *stream, char *format, <address-list>);
     char fgets(char *string, int n, FILE *steam);
     int fgetc(FILE *steam);
    fscanf()函数的用法与scanf()函数相似,   只是它是从文件中读到信息。
fscanf()函数的返回值为EOF(即-1), 表明读错误, 否则读数据成功。fgets()函
数从文件中读取至多n-1个字符(n用来指定字符数), 并把它们放入string指向的
字符串中, 在读入之后自动向字符串未尾加一个空字符, 读成功返回string指针,
失败返回一个空指针。fgetc()函数返回文件当前位置的一个字符, 读错误时返
EOF。
    下面程序读取例11产生的test.dat文件, 并将读出的结果显示在屏幕上。
    12
     #include<stdio.h>
     main()
     {
          char *s, m[20];
          int i;
          FILE *fp;
          fp=fopen("test.dat", "r");    /*打开文字文件只读*/
          fgets(s, 24, fp);             /*从文件中读取23个字符*/
          printf("%s", s);              /*输出所读的字符串*/
          fscanf(fp, "%d", &i);         /*读取整型数*/
          printf("%d", i);              /*输出所读整型数*/
          putchar(fgetc(fp));           /*读取一个字符同时输出*/
          fgets(m, 17, fp);             /*读取16个字符*/
          puts(m);                      /*输出所读字符串*/
          fclose(fp);                   /*关闭文件*/
          getch();                      /*等待任一键*/
     }
    运行后屏幕显示:
    Your score of TOEFL is: 617
    That's good news
    如果将上例中fscanf(fp, "%d", &i)改为fscanf(fp, "%s", m), 再将其后
的输出语句改为printf("%s", m), 则可得出同样的结果。由此可见Turbo C2. 0
中只要是读文字文件, 则不论是字符还是数字都将按其ASCII值处理。 另外还要
说明的一点就是fscanf()函数读到空白符时, 便自动结束, 在使用时要特别注意。
 
    3. 文件的随机读写
    有时用户想直接读取文件中间某处的信息, 若用文件的顺序读写必须从文件
头开始直到要求的文件位置再读, 这显然不方便。Turbo C2.0提供了一组文件的
随机读写函数, 即可以将文件位置指针定位在所要求读写的地方直接读写。
    文件的随机读写函数如下:
    int fseek (FILE *stream, long offset, int fromwhere);
    int fread(void *buf, int size, int count, FILE *stream);
    int fwrite(void *buf, int size, int count, FILE *stream);
    long ftell(FILE *stream);
    fseek()函数的作用是将文件的位置指针设置到从fromwhere开始的第offset
字节的位置上, 其中fromwhere是下列几个宏定义之一:
    文件位置指针起始计算位置fromwhere
━━━━━━━━━━━━━━━━━━━━━━━━━━━
    符号常数        数值           含义
───────────────────────────
    SEEK_SET          0        从文件开头
    SEEK_CUR          1        从文件指针的现行位置
    SEEK_END          2        从文件末尾
━━━━━━━━━━━━━━━━━━━━━━━━━━━
    offset是指文件位置指针从指定开始位置(fromwhere指出的位置)跳过的字
节数。它是一个长整型量, 以支持大于64K字节的文件。fseek()函数一般用于对
二进制文件进行操作。
    fseek()函数返回0时表明操作成功, 返回非0表示失败。
    下面程序从二进制文件test_b.dat中读取第8个字节。
    13:
     #include<stdio.h>
    main()
     {
          FILE *fp;
          if((fp=fopen("test_b.dat", "rb"))==NULL)
            {
              printf("Can't open file");
              exit(1);
            }
          fseek(fp, 8. 1, SEEK_SET);
          fgetc(fp);
          fclose(fp);
     }
    fread()函数是从文件中读count个字段, 每个字段长度为size个字节, 并把
它们存放到buf指针所指的缓冲器中。
    fwrite()函数是把buf指针所指的缓冲器中, 长度为size个字节的count个字
段写到stream指向的文件中去。
    随着读和写字节数的增大, 文件位置指示器也增大, 读多少个字节, 文件位
置指示器相应也跳过多少个字节。读写完毕函数返回所读和所写的字段个数。
    ftell()函数返回文件位置指示器的当前值, 这个值是指示器从文件头开始
算起的字节数, 返回的数为长整型数, 当返回-1时, 表明出现错误。
    下面程序把一个浮点数组以二进制方式写入文件test_b.dat中。
    14:
     #include <stdio.h>
     main()
     {
          float f[6]={3.2, -4.34, 25.04, 0.1, 50.56, 80.5};
                         /*定义浮点数组并初始化*/
          int i;
          FILE *fp;
          fp=fopen("test_b.dat", "wb"); /*创建一个二进制文件只写*/
          fwrite(f, sizeof(float), 6, fp);/*6个浮点数写入文件中*/
          fclose(fp);                   /*关闭文件*/
     }
    下面例子从test_b.dat文件中读100个整型数, 并把它们放到dat数组中。
    15:
     #include <stdio.h>
     main()
     {
          FILE *fp;
          int dat[100];
          fp=fopen("test_b.dat", "rb");/*打开一个二进制文件只读*/
          if(fread(dat, sizeof(int), 100, fp)!=100)
                                        /*判断是否读了100个数*/
            {
               if(feof(fp))
                 printf("End of file"); /*不到100个数文件结束*/
               else
                 printf("Read error"); /*读数错误*/
          fclose(fp);                   /*关闭文件*/
     }
    注意:
    当用标准文件函数对文件进行读写操作时, 首先将所读写的内容放进缓冲区,
即写函数只对输出缓冲区进行操作, 读函数只对输入缓冲区进行操作。例如向一
个文件写入内容, 所写的内容将首先放在输出缓冲区中, 直到输出缓冲区存满或
使用fclose()函数关闭文件时, 缓冲区的内容才会写入文件中。若无fclose()
函数, 则不会向文件中存入所写的内容或写入的文件内容不全。有一个对缓冲区
进行刷新的函数, 即fflush(), 其调用格式为:
    int fflush(FILE *stream);
    该函数将输出缓冲区的内容实际写入文件中, 而将输入缓冲区的内容清除掉。
 
    4. feof()rewind()函数
    这两个函数的调用格式为:
     int feof(FILE *stream);
     int rewind(FILE *stream);
    feof()函数检测文件位置指示器是否到达了文件结尾, 若是则返回一个非0
, 否则返回0。这个函数对二进制文件操作特别有用, 因为二进制文件中, 文
件结尾标志EOF也是一个合法的二进制数, 只简单的检查读入字符的值来判断文
件是否结束是不行的。如果那样的话, 可能会造成文件未结尾而被认为结尾, 所
以就必须有feof()函数。
    下面的这条语句是常用的判断文件是否结束的方法。
     while(!feof(fp))
        fgetc(fp);
    while为循环语句, 将在下面介绍。
    rewind()函数用于把文件位置指示器移到文件的起点处, 成功时返回0, 否
, 返回非0值。
 
 
    1.2.2 非标准文件函数
    这类函数最早用于UNIX操作系统, ANSI标准未定义,   但有时也经常用到,
DOS 3.0以上版本支持这些函数。它们的头文件为io.h。
    一、文件的打开和关闭
    1. open()函数
    open()函数的作用是打开文件, 其调用格式为:
     int open(char *filename, int access);
    该函数表示按access的要求打开名为filename的文件, 返回值为文件描述字,
其中access有两部分内容: 基本模式和修饰符, 两者用" "("或")方式连接。修
饰符可以有多个, 但基本模式只能有一个。access的规定如表3-2。
               3-2 access的规定
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
基本模式    含义    修饰符         含 义
────────────────────────────
O_RDONLY    只读   O_APPEND   文件指针指向末尾
O_WRONLY    只写   O_CREAT    文件不存在时创建文件,
                              属性按基本模式属性
O_RDWR      读写   O_TRUNC    若文件存在, 将其长度
                              缩为0, 属性不变
                   O_BINARY   打开一个二进制文件
                   O_TEXT     打开一个文字文件
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    open()函数打开成功, 返回值就是文件描述字的值(非负值), 否则返回-1。
 
    2. close()函数
    close()函数的作用是关闭由open()函数打开的文件, 其调用格式为:
     int close(int handle);
    该函数关闭文件描述字handle相连的文件。
 
               读写函数
1.                    read()函数
    read()函数的调用格式为:
     int read(int handle, void *buf, int count);
    read()函数从handle(文件描述字)相连的文件中, 读取count个字节放到buf
所指的缓冲区中, 返回值为实际所读字节数, 返回-1表示出错。返回0 表示文件
结束。
 
2.                    write()函数
    write()函数的调用格式为:
     int write(int handle, void *buf, int count);
    write()函数把count个字节从buf指向的缓冲区写入与handle相连的文件中,
返回值为实际写入的字节数。
 
               随机定位函数
1.                    lseek()函数
    lseek()函数的调用格式为:
     int lseek(int handle, long offset, int fromwhere);
    该函数对与handle相连的文件位置指针进行定位, 功能和用法与fseek() 函
数相同。
 
2.                    tell()函数
    tell()函数的调用格式为:
     long tell(int handle);
    该函数返回与handle相连的文件现生位置指针, 功能和用法与ftell()相同。
     1.3 控制流程语句
    Turbo C2.0提供了丰富、灵活的控制流程语句, 主要有:条件语句、循环语
句和开关语句。下面将对这些语句作详细介绍。
 
 
    1.3.1 条件语句
    象其它语言一样Turbo C2.0也提供条件语句。在Turbo C2.0中条件语句的一
般形式为:
    if(表达式)
       语句1;
    else
       语句2;
    上述结构表示: 如果表达式的值为非0(TURE)即真, 则执行语句1, 执行完语
1从语句2后开始继续向下执行; 如果表达式的值为0(FALSE)即假, 则跳过语句
1而执行语句2。所谓表达式是指关系表达式和逻辑表达式的结合式, 关于表达式
前面已作过介绍, 这是不再重复。
    注意:
    1. 条件执行语句中"else 语句2;"部分是选择项, 可以缺省, 此时条件语句
变成:
      if(表达式) 语句1;
    表示若表达式的值为非0则执行语句1 , 否则跳过语句1继续执行。
    2. 如果语句1或语句2有多于一条语句要执行时, 必须使用"{"和"}" 把这些
语句包括在其中, 此时条件语句形式为:
      if(表达式)
      {
        语句体1;
      }
      else
      {
          语句体2;
      }
    3. 条件语句可以嵌套, 这种情况经常碰到, 但条件嵌套语句容易出错, 其
原因主要是不知道哪个if对应哪个else。
    例如:
      if(x>20||x<-10)
      if(y<=100&&y>x)
          printf("Good");
      else
          printf("Bad");
    对于上述情况, Turbo C2.0规定: else语句与最近的一个if语句匹配, 上例
中的else与if(y<=100&&y>x)相匹配。为了使else与if(x>20||x<-10)相匹配, 必
须用花括号。如下所示:
      if(x>20||x<-10)
      {
          if(y<=100&&y>x)
            printf("Good");
       }
       else
          printf("Bad");
    4. 可用阶梯式if-else-if结构。
    阶梯式结构的一般形式为:
      if(表达式1)
         语句1;
      else if(表达式2)
        语句2;
      else if(表达式3)
        语句3;
          .
          .
          .
      else
        语句n;
    这种结构是从上到下逐个对条件进行判断, 一旦发现条件满点足就执行与它
有关的语句, 并跳过其它剩余阶梯; 若没有一个条件满足, 则执行最后一个else
语句n。最后这个else常起着"缺省条件"的作用。
    同样, 如果每一个条件中有多于一条语句要执行时, 必须使用"{"和"}"把这
些语句包括在其中。
 
 
    1.3.2 循环语句
    Turbo C2.0提供三种基本的循环语句: for语句、while语句和do-while语句。
 
    1.3.2.1 for循环
    for循环是开界的。它的一般形式为:
     for(<初始化>; <条件表过式>; <增量>)
          语句;
    初始化总是一个赋值语句, 它用来给循环控制变量赋初值; 条件表达式是一
个关系表达式, 它决定什么时候退出循环; 增量定义循环控制变量每循环一次后
按什么方式变化。这三个部分之间用";"分开。
    例如:
     for(i=1; i<=10; i++)
          语句;
    上例中先给i赋初值1, 判断i是否小于等于10, 若是则执行语句, 之后值增
1。再重新判断, 直到条件为假, 即i>10时, 结束循环。
    注意:
    1. for循环中语句可以为语句体, 但要用"{"和"}"将参加循环的语句括起来。
    2. for循环中的"初始化"、"条件表达式"和"增量"都是选择项, 即可以缺省,
";"不能缺省。省略了初始化, 表示不对循环控制变量赋初值。省略了条件
表达式, 则不做其它处理时便成为死循环。省略了增量, 则不对循环控制变量进
行操作, 这时可在语句体中加入修改循环控制变量的语句。
    3. for循环可以有多层嵌套。
    16:
     main()
     {
          int i, j, k;
          printf("i j k/n");
          for (i=0; i<2; i++)
            for(j=0; j<2; j++)
               for(k=0; k<2; k++)
                  printf(%d %d %d/n", i, j, k);
     }
    输出结果为:
     i j k
     0 0 0
     0 0 1
     0 1 0
     0 1 1
     1 0 0
     1 0 1
     1 1 0
     1 1 1
 
    1.3.2.2 while循环
    while循环的一般形式为:
      while(条件)
          语句;
    while循环表示当条件为真时, 便执行语句。直到条件为假才结束循环。并
继续执行循环程序外的后续语句。
    17:
     #include<stdio.h>
     main()
     {
          char c;
          c='/0';             /*初始化c*/
          while(c!='/X0D')    /*回车结束循环*/
            c=getche();       /*带回显的从键盘接收字符*/
     }
    上例中, while循环是以检查c是否为回车符开始, 因其事先被初始化为空,
所以条件为真, 进入循环等待键盘输入字符; 一旦输入回车, 则c='/X0D', 条件
为假, 循环便告结束。
    for循环一样, while循环总是在循环的头部检验条件, 这就意味着循环可
能什么也不执行就退出。
    注意:
    1. while循环体内也允许空语句。
    例如:
     while((c=getche())!='/X0D');
    这个循环直到键入回车为止。
    2. 可以有多层循环嵌套。
    3. 语句可以是语句体, 此时必须用"{"和"}"括起来。
    18:
     #include<stdio.h>
     main()
     {
          char c, fname[13];
          FILE *fp;                /*定义文件指针*/
          printf("File name:");    /*提示输入文件名*/
          scanf("%s", fname);      /*等待输入文件名*/
          fp=fopen(fname, "r");    /*打开文件只读*/
          while((c=fgetc(fp)!=EOF) /*读取一个字符并判断是否到文件结束*/
               putchar(c);         /*文件未结束时显示该字符*/
 
 
 
     }
 
    1.3.2.3 do-while 循环
    do-while 循环的一般格式为:
       do
           语句;
       while(条件);
    这个循环与while循环的不同在于: 它先执行循环中的语句, 然后再判断条
件是否为真, 如果为真则继续循环; 如果为假, 则终止循环。因此, do-while循
环至少要执行一次循环语句。
    同样当有许多语句参加循环时, 要用"{"和"}"把它们括起来。
 
 
    1.3.3 开关语句
    在编写程序时, 经常会碰到按不同情况分转的多路问题, 这时可用嵌套if
-else-fi语句来实现, 但if-else-if语句使用不方便, 并且容易出错。对这种情
, Turbo C2.0提供了一个开关语句。开关语句格式为:
          switch(变量)
          {
               case 常量1:
                    语句1或空;
               case 常量2:
                    语句2或空;
                    .
                    .
                    .
               case 常量n;
                    语句n或空;
               default:
                    语句n+1或空;
          }
    执行switch开关语句时, 将变量逐个与case后的常量进行比较, 若与其中一
个相等, 则执行该常量下的语句, 若不与任何一个常量相等, 则执行default 后
面的语句。
    注意:
    1. switch中变量可以是数值, 也可以是字符。
    2. 可以省略一些case和default。
    3. 每个case或default后的语句可以是语句体, 但不需要使用"{"和"}"括起
来。
    下例的switch中变量为整数型。
    19:
     main()
     {
          int test;
          for(test=0; test<=10; test++)
          {
               switch(test)   /*变量为整型数的开关语句*/
               {
                    case 1:
                         printf("%d/n", test);
                         break;    /*退出开关语句*/
                    case 2:
                         printf("%d/n", test);
                         break;
                    case 3:
                         printf("%d/n", test);
                         break;
                    default:
                         puts("Error");
                         break;
               }
          }
     }
    下例的switch中变量为字符型。
    20:
     #include<stdio.h>
     main()
     {
          char c;
          while(c!=27)                  /*循环直到按Esc键结束*/
          {
               c=getch();               /*从键盘不回显接收一个字符*/
               switch(c)
               {
                    case 'A':           /*接收的字符为'A'*/
                         putchar(c);
                         break;         /*退出开关语句*/
                    case 'B':
                         putchar(c);
                         break;
                    default:            /*接收的字符非'A'和'B'*/
                         puts("Error");
                         break;
               }
          }
     }
 
 
 
    1.3.4 breakcontinue和goto语句
 
    1.3.4.1 break语句
    break语句通常用在循环语句和开关语句中。当break用于开关语句switch中
, 可使程序跳出switch而执行switch以后的语句; 如果没有break语句, 则将
成为一个死循环而无法退出。break在switch 中的用法已在前面介绍开关语句时
的例子中碰到, 这里不再举例。
    break语句用于do-while、for、while循环语句中时, 可使程序终止循环
而执行循环后面的语句, 通常break语句总是与if语句联在一起。即满足条件时
便跳出循环。
    19:
     main()
     {
          int i=0;
          char c;
          while(1)                 /*设置循环*/
          {
               c='/0';             /*变量赋初值*/
               while(c!=13&&c!=27) /*键盘接收字符直到按回车或Esc键*/
               {
                    c=getch();
                    printf("%c/n", c);
               }
               if(c==27)
                    break;          /*判断若按Esc键则退出循环*/
               i++;
               printf("The No. is %d/n", i);
          }
          printf("The end");
     }
    注意:
    1. break语句对if-else的条件语句不起作用。
    2. 在多层循环中, 一个break语句只向外跳一层。
 
    1.3.4.2 continue 语句
    continue语句的作用是跳过循环本中剩余的语句而强行执行下一次循环。
    continue语句只用在for、while、do-while等循环体中, 常与if条件语句一
起使用, 用来加速循环。
    20:
     main()
     {
          char c;
          while(c!=0X0D)      /*不是回车符则循环*/
          {
               c=getch();
               if(c==0X1B)
                    continue; /*若按Esc键不输出便进行下次循环*/
               printf("%c/n", c);
          }
     }
 
    1.3.4.3 goto 语句
    goto语句是一种无条件转移语句, 与BASIC中的goto语句相似。goto 语句的
使用格式为:
    goto 标号;
    其中标号是Turbo C2.0中一个有效的标识符, 这个标识符加上一个":" 一起
出现在函数内某处, 执行goto语句后, 程序将跳转到该标号处并执行其后的语句。
另外标号必须与goto语句同处于一个函数中, 但可以不在一个循环层中。通常
goto语句与if条件语句连用, 当满足某一条件时, 程序跳到标号处运行。
    goto语句通常不用, 主要因为它将使程序层次不清, 且不易读, 但在多层嵌
套退出时, 用goto语句则比较合理。
    19用goto语句时变为:
    21:
     main()
     {
          int i=0;
          char c;
          while(1)
          {
               c='/0';
               while(c!=13)
               {
                    c=getch();
                    if(c==27)
                      goto quit;
                    printf("%c/n", c);
               }
               i++;
               printf("The No. is %d/n", i);
          }
          quit:
               printf("The end");
 
 
                             返回目录
     }
                  指针、结构、联合和枚举
    本节专门对第二节曾讲述过的指针作一详述。并介绍Turbo C新的数据类型:
结构、联合和枚举, 其中结构和联合是以前讲过的五种基本数据类型(整型、浮
点型、字符型、指针型和无值型)的组合。 枚举是一个被命名为整型常数的集合。
最后对类型说明(typedef)和预处理指令作一阐述。
 
                             针(point)
 
    学习Turbo C语言, 如果你不能用指针编写有效、正确和灵活的程序, 可以
认为你没有学好C语言。指针、地址、数组及其相互关系是C语言中最有特色的部
分。规范地使用指针, 可以使程序达到简单明了, 因此, 我们不但要学会如何正
确地使用指针, 而且要学会在各种情况下正确地使用指针变量。
 
    1. 指针和地址
    1.1 指针基本概念及其指针变量的定义
    1.1.1 指针变量的定义
    我们知道变量在计算机内是占有一块存贮区域的, 变量的值就存放在这块区
域之中, 在计算机内部, 通过访问或修改这块区域的内容来访问或修改相应的变
量。Turbo C语言中, 对于变量的访问形式之一, 就是先求出变量的地址, 然后
再通过地址对它进行访问, 这就是这里所要论述的指针及其指针变量。
    所谓变量的指针, 实际上指变量的地址。变量的地址虽然在形式上好象类似
于整数, 但在概念上不同于以前介绍过的整数, 它属于一种新的数据类型, 即指
针类型。Turbo C中, 一般用"指针"来指明这样一个表达式&x的类型, 而用 "地
"作为它的值, 也就是说, 若x为一整型变量, 则表达式&x的类型是指向整数的
指针, 而它的值是变量x的地址。同样, 若
     double d;
&d的类型是指向以精度数d的指针, 而&d的值是双精度变量d的地址。所以, 指
针和地址是用来叙述一个对象的两个方面。虽然&x、&d的值分别是整型变量x 和
双精度变量d的地址, 但&x、&d的类型是不同的, 一个是指向整型变量x的指针,
而另一个则是指向双精度变量d的指针。在习惯上, 很多情况下指针和地址这两
个术语混用了。
    我们可以用下述方法来定义一个指针类型的变量。
     int *ip;
首先说明了它是一指针类型的变量, 注意在定义中不要漏写符号"*", 否则它为
一般的整型变量了。另外, 在定义中的int 表示该指针变量为指向整型数的指针
类型的变量, 有时也可称ip为指向整数的指针。ip是一个变量, 它专门存放整型
变量的地址。
    指针变量的一般定义为:
     类型标识符 *标识符;
    其中标识符是指针变量的名字, 标识符前加了"*"号, 表示该变量是指针变
, 而最前面的"类型标识符"表示该指针变量所指向的变量的类型。一个指针变
量只能指向同一种类型的变量, 也就是讲, 我们不能定义一个指针变量, 既能指
向一整型变量又能指向双精度变量。
    指针变量在定义中允许带初始化项。如:
      int i, *ip=&i;
注意, 这里是用&i对ip初始化, 而不是对*ip初始化。和一般变量一样, 对于外
部或静态指针变量在定义中若不带初始化项, 指针变量被初始化为NULL, 它的值
0。Turbo C中规定, 当指针值为零时, 指针不指向任何有效数据, 有时也称指
针为空指针。因此, 当调用一个要返回指针的函数(第五节中介绍)时, 常使用返
回值为NULL来指示函数调用中某些错误情况的发生。
    1.1.2 指针变量的引用
    既然在指针变量中只能存放地址, 因此, 在使用中不要将一个整数赋给一指
针变量。下面的赋值是不合法的:
     int *ip;
     ip=100;
假设
     int i=200, x;
     int *ip;
我们定义了两个整型变量i, x, 还定义了一个指向整型数的指针变量ip。i, x中
可存放整数, 而ip中只能存放整型变量的地址。我们可以把i的地址赋给ip:
     ip=&i;
此时指针变量ip指向整型变量i, 假设变量i的地址为1800, 这个赋值可形象理解
为下图所示的联系。
            ip               i
        ┏━━━┓       ┏━━━┓
        1800 ╂──→ ┃ 200 ┃
        ┗━━━┛       ┗━━━┛
            1. 给指针变量赋值
以后我们便可以通过指针变量ip间接访问变量i, 例如:
     x=*ip;
运算符*访问以ip为地址的存贮区域, 而ip中存放的是变量i的地址, 因此, *ip
访问的是地址为1800的存贮区域(因为是整数, 实际上是从1800开始的两个字节),
它就是i所占用的存贮区域, 所以上面的赋值表达式等价于
     x=i;
    另外, 指针变量和一般变量一样, 存放在它们之中的值是可以改变的, 也就
是说可以改变它们的指向, 假设
     int i, j, *p1, *p2;
     i='a';
     j='b';
     p1=&i;
     p2=&j;
则建立如下图所示的联系:
            p1               i
        ┏━━━┓       ┏━━━┓
              ╂──→ ┃ 'a' ┃
        ┗━━━┛       ┗━━━┛
            p2               i
        ┏━━━┓       ┏━━━┓
              ╂──→ ┃ 'b' ┃
        ┗━━━┛       ┗━━━┛
             2. 赋值运算结果
这时赋值表达式:
     p2=p1
就使p2与p1指向同一对象i, 此时*p2就等价于i, 而不是j, 图2.就变成图3.所示:
            p1               i
        ┏━━━┓       ┏━━━┓
              ╂──→ ┃ 'a' ┃
        ┗━━━┛ ┌→ ┗━━━┛
            p2             j
        ┏━━━┓ │   ┏━━━┓
              ╂─┘   ┃ 'b' ┃
        ┗━━━┛       ┗━━━┛
            3. p2=p1时的情形
如果执行如下表达式:
     *p2=*p1;
则表示把p1指向的内容赋给p2所指的区域, 此时图2.就变成图4.所示
            p1               i
        ┏━━━┓       ┏━━━┓
              ╂──→ ┃ 'a' ┃
        ┗━━━┛       ┗━━━┛
            p2               j
        ┏━━━┓       ┏━━━┓
              ╂──→ ┃ 'a' ┃
        ┗━━━┛       ┗━━━┛
            4. *p2=*p1时的情形
    通过指针访问它所指向的一个变量是以间接访问的形式进行的, 所以比直接
访问一个变量要费时间, 而且不直观, 因为通过指针要访问哪一个变量, 取决于
指针的值(即指向), 例如"*p2=*p1;"实际上就是"j=i;", 前者不仅速度慢而且目
的不明。但由于指针是变量, 我们可以通过改变它们的指向, 以间接访问不同的
变量, 这给程序员带来灵活性, 也使程序代码编写得更为简洁和有效。
    指针变量可出现在表达式中, 设
     int x, y *px=&x;
指针变量px指向整数x, 则*px可出现在x能出现的任何地方。例如:
     y=*px+5; /*表示把x的内容加5并赋给y*/
     y=++*px; /*px的内容加上1之后赋给y [++*px相当于++(px)]*/
     y=*px++; /*相当于y=*px; px++*/
 
    1.2. 地址运算
    指针允许的运算方式有:
    (1). 指针在一定条件下, 可进行比较, 这里所说的一定条件, 是指两个指
针指向同一个对象才有意义, 例如两个指针变量p, q指向同一数组, 则<, >, >=,
<=, ==等关系运算符都能正常进行。若p==q为真, 则表示p, q指向数组的同一元
; 若p<q为真, 则表示p所指向的数组元素在q所指向的数组元素之前(对于指向
数组元素的指针在下面将作详细讨论)。
    (2). 指针和整数可进行加、减运算。设p是指向某一数组元素的指针, 开始
时指向数组的第0号元素, 设n为一整数, 则
     p+n
就表示指向数组的第n号元素(下标为n的元素)。
    不论指针变量指向何种数据类型, 指针和整数进行加、减运算时, 编译程序
总根据所指对象的数据长度对n放大, 在一般微机上, char放大因子为1, int、
short放大因子为2, long和float放大因子为4, double放大因子为8。 对于下面
讲述到的结构或联合, 也仍然遵守这一原则。
    (3). 两个指针变量在一定条件下, 可进行减法运算。设p, q指向同一数组,
p-q的绝对值表示p所指对象与q所指对象之间的元素个数。其相减的结果遵守
对象类型的字节长度进行缩小的规则。
 
    2. 指针和数组
    指针和数组有着密切的关系, 任何能由数组下标完成的操作也都可用指针来
实现, 但程序中使用指针可使代码更紧凑、更灵活。
 
    2.1. 指向数组元素的指针
    我们定义一个整型数组和一个指向整型的指针变量:
          int a[10], *p;
和前面介绍过的方法相同, 可以使整型指针p指向数组中任何一个元素, 假定给
出赋值运算
          p=&a[0];
此时, p指向数组中的第0号元素, 即a[0], 指针变量p中包含了数组元素a[0] 的
地址, 由于数组元素在内存中是连续存放的, 因此, 我们就可以通过指针变量p
及其有关运算间接访问数组中的任何一个元素。
    Turbo C, 数组名是数组的第0号元素的地址, 因此下面两个语句是等价的
     p=&a[0];
     p=a;
根据地址运算规则, a+1为a[1]的地址, a+i就为a[i]的地址。
    下面我们用指针给出数组元素的地址和内容的几种表示形式。
    (1). p+ia+i均表示a[i]的地址, 或者讲, 它们均指向数组第i号元素, 即
指向a[i]。
    (2). *(p+i)*(a+i)都表示p+i和a+i所指对象的内容, 即为a[i]。
    (3). 指向数组元素的指针, 也可以表示成数组的形式, 也就是说, 它允许
指针变量带下标, 如p[i]与*(p+i)等价。
    假若:      p=a+5;
p[2]就相当于*(p+2), 由于p指向a[5], 所以p[2]就相当于a[7]。而p[-3]就相
当于*(p-3), 它表示a[2]。
 
    2.2. 指向二维数组的指针
    2.2.1. 二维数组元素的地址
    为了说明问题, 我们定义以下二维数组:
     int a[3][4]={{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
a为二维数组名, 此数组有3行4列, 共12个元素。但也可这样来理解, 数组a由三
个元素组成: a[0], a[1], a[2]。而它匀中每个元素又是一个一维数组, 且都含
4个元素 (相当于4列), 例如, a[0]所代表的一维数组所包含的 4 个元素为
a[0][0], a[0][1], a[0][2], a[0][3]。如图5.所示:
        ┏━━━━┓    ┏━┳━┳━┳━┓
 a─→ ┃ a[0] ┃─→┃0 ┃1 ┃2 ┃3 ┃
        ┣━━━━┫    ┣━╋━╋━╋━┫
         a[1] ┃─→┃4 ┃5 ┃6 ┃7 ┃
        ┣━━━━┫    ┣━╋━╋━╋━┫
         a[2] ┃─→┃8 ┃9 ┃10┃11┃
        ┗━━━━┛    ┗━┻━┻━┻━┛
                    5.
    但从二维数组的角度来看, a代表二维数组的首地址, 当然也可看成是二维
数组第0行的首地址。a+1就代表第1行的首地址, a+2就代表第2行的首地址。如
果此二维数组的首地址为1000, 由于第0行有4个整型元素, 所以a+1为1008, a+2
也就为1016。如图6.所示
                            a[3][4]
                   a    ┏━┳━┳━┳━┓
              (1000)─→┃0 ┃1 ┃2 ┃3 ┃
                   a+1 ┣━╋━╋━╋━┫
              (1008)─→┃4 ┃5 ┃6 ┃7 ┃
                   a+2 ┣━╋━╋━╋━┫
              (1016)─→┃8 ┃9 ┃10┃11┃
                        ┗━┻━┻━┻━┛
                              6.
    既然我们把a[0], a[1], a[2]看成是一维数组名, 可以认为它们分别代表它
们所对应的数组的首地址, 也就是讲, a[0]代表第 0 行中第 0 列元素的地址,
&a[0][0], a[1]是第1行中第0列元素的地址, 即&a[1][0], 根据地址运算规则,
a[0]+1即代表第0行第1列元素的地址, 即&a[0][1], 一般而言, a[i]+j即代表第
i行第j列元素的地址, 即&a[i][j]。
    另外, 在二维数组中, 我们还可用指针的形式来表示各元素的地址。如前所
, a[0]与*(a+0)等价, a[1]与*(a+1)等价, 因此a[i]+j就与*(a+i)+j等价, 它
表示数组元素a[i][j]的地址。
    因此, 二维数组元素a[i][j]可表示成*(a[i]+j)或*(*(a+i)+j), 它们都与
a[i][j]等价, 或者还可写成(*(a+i))[j]。
    另外, 要补充说明一下, 如果你编写一个程序输出打印a和*a, 你可发现它
们的值是相同的, 这是为什么呢? 我们可这样来理解: 首先, 为了说明问题, 我
们把二维数组人为地看成由三个数组元素a[0], a[1], a[2]组成, 将a[0], a[1],
a[2]看成是数组名它们又分别是由4个元素组成的一维数组。因此, a表示数组第
0行的地址, 而*a即为a[0], 它是数组名, 当然还是地址, 它就是数组第0 行第0
列元素的地址。
 
    2.2.2 指向一个由n个元素所组成的数组指针
    Turbo C中, 可定义如下的指针变量:
      int (*p)[3];
    指针p为指向一个由3个元素所组成的整型数组指针。在定义中, 圆括号是不
能少的, 否则它是指针数组, 这将在后面介绍。这种数组的指针不同于前面介绍
的整型指针, 当整型指针指向一个整型数组的元素时, 进行指针(地址)加1运算,
表示指向数组的下一个元素, 此时地址值增加了2(因为放大因子为2), 而如上所
定义的指向一个由3个元素组成的数组指针, 进行地址加1运算时, 其地址值增加
6(放大因子为2x3=6), 这种数组指针在Turbo C中用得较少, 但在处理二维数
组时, 还是很方便的。例如:
          int a[3][4], (*p)[4];
          p=a;
    开始时p指向二维数组第0行, 当进行p+1运算时, 根据地址运算规则, 此时
放大因子为4x2=8, 所以此时正好指向二维数组的第1行。和二维数组元素地址计
算的规则一样, *p+1指向a[0][1], *(p+i)+j则指向数组元素a[i][j]。
     1
     int a[3] [4]={
     {1,3,5,7},
     {9,11,13,15},
     {17,19,21,23}
    };
    main()
    {
         int i,(*b)[4];
           b=a+1;                  /* b指向二维数组的第1行, 此时*b[0]或
                                     **ba[1][0] */
         for(i=1;i<=4;b=b[0]+2,i++)/* 修改b的指向, 每次增加2 */
           printf("%d/t",*b[0]);
         printf("/n");
         for (i=0; i<2; i++) {
           b=a+i;                  /* 修改b的指向, 每次跳过二维数组的
                                      一行 */
           printf("%d/t",*(b[i]+1));
        }
         printf ("/n");
     }
    程序运行结果如下:
     9    13   17   21
     3    11   19
 
    3. 字符指针
    我们已经知道, 字符串常量是由双引号括起来的字符序列, 例如:
          "a string"
就是一个字符串常量, 该字符串中因为字符a后面还有一个空格字符, 所以它由8
个字符序列组成。在程序中如出现字符串常量C 编译程序就给字符串常量按排一
存贮区域, 这个区域是静态的, 在整个程序运行的过程中始终占用, 平时所讲的
字符串常量的长度是指该字符串的字符个数, 但在按排存贮区域时, C 编译程序
还自动给该字符串序列的末尾加上一个空字符'/0', 用来标志字符串的结束, 因
此一个字符串常量所占的存贮区域的字节数总比它的字符个数多一个字节。
    Turbo C中操作一个字符串常量的方法有:
    (1). 把字符串常量存放在一个字符数组之中, 例如:
          char s[]="a string";
数组s共有9个元素所组成, 其中s[8]中的内容是'/0'。实际上, 在字符数组定义
的过程中, 编译程序直接把字符串复写到数组中, 即对数组s初始化。
    (2). 用字符指针指向字符串, 然后通过字符指针来访问字符串存贮区域。
当字符串常量在表达式中出现时, 根据数组的类型转换规则, 它被转换成字符指
针。因此, 若我们定义了一字符指针cp:
     char *cp;
于是可用:
     cp="a string";
使cp指向字符串常量中的第0号字符a, 如图7.所示。
            cp
        ┏━━━┓     ┏━┳━┳━┳━┳━┳━┳━┳━┳━┓
            ─╂─→ ┃a ┃ ┃s ┃t ┃r ┃i ┃n ┃g ┃/0┃
        ┗━━━┛     ┗━┻━┻━┻━┻━┻━┻━┻━┻━┛
                              7.
以后我们可通过cp来访问这一存贮区域, 如*cp或cp[0]就是字符a, 而cp[i]或
*(cp+i)就相当于字符串的第i号字符, 但企图通过指针来修改字符串常量的行为
是没有意义的。
 
    4. 指针数组
    因为指针是变量, 因此可设想用指向同一数据类型的指针来构成一个数组,
这就是指针数组。数组中的每个元素都是指针变量, 根据数组的定义, 指针数组
中每个元素都为指向同一数据类型的指针。指针数组的定义格式为:
     类型标识 *数组名[整型常量表达式];
    例如:
       int *a[10];
定义了一个指针数组, 数组中的每个元素都是指向整型量的指针, 该数组由10个
元素组成, 即a[0], a[1], a[2], ..., a[9], 它们均为指针变量。a为该指针数
组名, 和数组一样, a是常量, 不能对它进行增量运算。a为指针数组元素a[0]的
地址, a+i为a[i]的地址, *a就是a[0], *(a+i)就是a[i]。
    为什么要定义和使用指针数组呢? 主要是由于指针数组对处理字符串提供了
更大的方便和灵活, 使用二维数组对处理长度不等的正文效率低, 而指针数组由
于其中每个元素都为指针变量, 因此通过地址运算来操作正文行是十分方便的。
    指针数组和一般数组一样, 允许指针数组在定义时初始化, 但由于指针数组
的每个元素是指针变量, 它只能存放地址, 所以对指向字符串的指针数组在说明
赋初值时, 是把存放字符串的首地址赋给指针数组的对应元素, 例如下面是一个
书写函数month_name(n), 此函数返回一个指向包含第n月名字的字符指针( 关于
函数, 第6节将专门介绍)。
    2: 打印1月至12月的月名:
     char *month_name(int n)
    {
          static char *name[]={
               "Illegal month",
               "January",
               "February",
               "March",
               "April",
               "May",
               "June",
               "July",
               "August",
               "September",
               "October",
               "November",
               "December"
          };
          return((n<1||n>12)?name[0]:name[n]);
     }
     main()
     {
          int i;
          for(i=0; i<13; i++)
               printf("%s/n", month_name(i));
                             构(struct)
    结构是由基本数据类型构成的、并用一个标识符来命名的各种变量的组合。
结构中可以使用不同的数据类型。
 
    1. 结构说明和结构变量定义
    Turbo C中, 结构也是一种数据类型, 可以使用结构变量, 因此, 象其它
类型的变量一样, 在使用结构变量时要先对其定义。
    定义结构变量的一般格式为:
     struct 结构名
     {
          类型 变量名;
          类型 变量名;
          ...
     } 结构变量;
    结构名是结构的标识符不是变量名。
    类型为第二节中所讲述的五种数据类型(整型、浮点型、字符型、指针型和
无值型)。
    构成结构的每一个类型变量称为结构成员, 它象数组的元素一样, 但数组中
元素是以下标来访问的, 而结构是按变量名字来访问成员的。
    下面举一个例子来说明怎样定义结构变量。
     struct string
     {
          char name[8];
          int age;
          char sex[2];
          char depart[20];
          float wage1, wage2, wage3, wage4, wage5;
     } person;
    这个例子定义了一个结构名为string的结构变量person,   如果省略变量名
person, 则变成对结构的说明。用已说明的结构名也可定义结构变量。这样定义
时上例变成:
     struct string
     {
          char name[8];
          int age;
          char sex[2];
          char depart[20];
          float wage1, wage2, wage3, wage4, wage5;
     };
     struct string person;
    如果需要定义多个具有相同形式的结构变量时用这种方法比较方便, 它先作
结构说明, 再用结构名来定义变量。
    例如:
     struct string Tianyr, Liuqi, ...;
    如果省略结构名, 则称之为无名结构, 这种情况常常出现在函数内部, 用这
种结构时前面的例子变成:
     struct
     {
          char name[8];
          int age;
          char sex[2];
          char depart[20];
          float wage1, wage2, wage3, wage4, wage5;
     } Tianyr, Liuqi;
 
    2. 结构变量的使用
    结构是一个新的数据类型, 因此结构变量也可以象其它类型的变量一样赋值、
运算, 不同的是结构变量以成员作为基本变量。
    结构成员的表示方式为:
          结构变量.成员名
    如果将"结构变量.成员名"看成一个整体, 则这个整体的数据类型与结构中
该成员的数据类型相同, 这样就可象前面所讲的变量那样使用。
    下面这个例子定义了一个结构变量, 其中每个成员都从键盘接收数据, 然后
对结构中的浮点数求和, 并显示运算结果, 同时将数据以文本方式存入一个名为
wage.dat的磁盘文件中。请注意这个例子中不同结构成员的访问。
    3:
     #include <stdio.h>
     main()
     {
          struct{                  /*定义一个结构变量*/
               char name[8];
               int age;
               char sex[2];
               char depart[20];
               float wage1, wage2, wage3, wage4, wage5;
          }a;
          FILE *fp;
          float wage;
          char c='Y';
          fp=fopen("wage.dat", "w");    /*创建一个文件只写*/
          while(c=='Y'||c=='y')         /*判断是否继续循环*/
          {
               printf("/nName:");
               scanf("%s", a.name);     /*输入姓名*/
               printf("Age:");
               scanf("%d", &a.wage);    /*输入年龄*/
               printf("Sex:");
               scanf("%d", a.sex);
               printf("Dept:");
               scanf("%s", a.depart);
               printf("Wage1:");
               scanf("%f", &a.wage1);   /*输入工资*/
               printf("Wage2:");
               scanf("%f", &a.wage2);
               printf("Wage3:");
               scanf("%f", &a.wage3);
               printf("Wage4:");
               scanf("%f", &a.wage4);
               printf("Wage5:");
               scanf("%f", &a.wage5);
               wage=a.wage1+a.wage2+a.wage3+a.wage4+a.wage5;
               printf("The sum of wage is %6.2f/n", wage);/*显示结果*/
               fprintf(fp, "%10s%4d%4s%30s%10.2f/n", /*结果写入文件*/
                            a.name, a.age, a.sex, a.depart, wage);
               while(1)
               {
                    printf("Continue?<Y/N>");
                    c=getche();
                    if(c=='Y'||c=='y'||c=='N'||c=='n')
                         break;
               }
          }
          fclose(fp);
     }
 
    3. 结构数组和结构指针
    结构是一种新的数据类型, 同样可以有结构数组和结构指针。
    一、结构数组
    结构数组就是具有相同结构类型的变量集合。假如要定义一个班级40个同学
的姓名、性别、年龄和住址, 可以定义成一个结构数组。如下所示:
     struct{
          char name[8];
          char sex[2];
          int age;
          char addr[40];
     }student[40];
    也可定义为:
     struct string{
          char name[8];
          char sex[2];
          int age;
          char addr[40];
     };
     struct string student[40];
    需要指出的是结构数组成员的访问是以数组元素为结构变量的, 其形式为:
          结构数组元素.成员名
    例如:
      student[0].name
      student[30].age
    实际上结构数组相当于一个二维构造, 第一维是结构数组元素, 每个元素是
一个结构变量, 第二维是结构成员。
    注意:
    结构数组的成员也可以是数组变量。
    例如:
     struct a
     {
          int m[3][5];
          float f;
          char s[20];
     }y[4];
    为了访问结构a中结构变量y[2]的这个变量, 可写成
       y[2].m[1][4]
 
    二、结构指针
    结构指针是指向结构的指针。它由一个加在结构变量名前的"*" 操作符来定
, 例如用前面已说明的结构定义一个结构指针如下:
     struct string{
          char name[8];
          char sex[2];
          int age;
          char addr[40];
     }*student;
    也可省略结构指针名只作结构说明, 然后再用下面的语句定义结构指针。
      struct string *student;
    使用结构指针对结构成员的访问, 与结构变量对结构成员的访问在表达方式
上有所不同。结构指针对结构成员的访问表示为:
       结构指针名->结构成员
    其中"->"是两个符号"-"和">"的组合, 好象一个箭头指向结构成员。例如要
给上面定义的结构中name和age赋值, 可以用下面语句:
     strcpy(student->name, "Lu G.C");
     student->age=18;
    实际上, student->name就是(*student).name的缩写形式。
    需要指出的是结构指针是指向结构的一个指针, 即结构中第一个成员的首地
, 因此在使用之前应该对结构指针初始化, 即分配整个结构长度的字节空间,
这可用下面函数完成, 仍以上例来说明如下:
     student=(struct string*)malloc(size of (struct string));
    size of (struct string)自动求取string结构的字节长度, malloc() 函数
定义了一个大小为结构长度的内存区域, 然后将其诈地址作为结构指针返回。
 
    注意:
    1. 结构作为一种数据类型, 因此定义的结构变量或结构指针变量同样有局
部变量和全程变量, 视定义的位置而定。
    2. 结构变量名不是指向该结构的地址, 这与数组名的含义不同, 因此若需
要求结构中第一个成员的首地址应该是&[结构变量名]。
    4. 结构的复杂形式
    一、嵌套结构
    嵌套结构是指在一个结构成员中可以包括其它一个结构, Turbo C 允许这种
嵌套。
    例如: 下面是一个有嵌套的结构
     struct string{
          char name[8];
          int age;
          struct addr address;
     } student;
    其中: addr为另一个结构的结构名, 必须要先进行, 说明, 即
     struct addr{
          char city[20];
          unsigned lon zipcode;
          char tel[14];
     }
    如果要给student结构中成员address结构中的zipcode赋值, 则可写成:
      student.address.zipcode=200001;
    每个结构成员名从最外层直到最内层逐个被列出, 即嵌套式结构成员的表达
方式是:
      结构变量名.嵌套结构变量名.结构成员名
    其中: 嵌套结构可以有很多, 结构成员名为最内层结构中不是结构的成员名。
 
    二、位结构
    位结构是一种特殊的结构, 在需按位访问一个字节或字的多个位时, 位结构
比按位运算符更加方便。
    位结构定义的一般形式为:
     struct位结构名{
          数据类型 变量名: 整型常数;
          数据类型 变量名: 整型常数;
     } 位结构变量;
    其中: 数据类型必须是int(unsigned或signed)。 整型常数必须是非负的整
, 范围是0~15, 表示二进制位的个数, 即表示有多少位。
    变量名是选择项, 可以不命名, 这样规定是为了排列需要。
    例如: 下面定义了一个位结构。
     struct{
          unsigned incon: 8; /*incon占用低字节的0~7共8位*/
          unsigned txcolor: 4;/*txcolor占用高字节的0~3位共4位*/
          unsigned bgcolor: 3;/*bgcolor占用高字节的4~6位共3位*/
          unsigned blink: 1; /*blink占用高字节的第7位*/
     }ch;
    位结构成员的访问与结构成员的访问相同。
    例如: 访问上例位结构中的bgcolor成员可写成:
      ch.bgcolor
 
    注意:
    1. 位结构中的成员可以定义为unsigned, 也可定义为signed, 但当成员长
度为1时, 会被认为是unsigned类型。因为单个位不可能具有符号。
    2. 位结构中的成员不能使用数组和指针, 但位结构变量可以是数组和指针,
如果是指针, 其成员访问方式同结构指针。
    3. 位结构总长度(位数), 是各个位成员定义的位数之和, 可以超过两个字
节。
    4. 位结构成员可以与其它结构成员一起使用。
    例如:
     struct info{
          char name[8];
          int age;
          struct addr address;
          float pay;
          unsigned state: 1;
          unsigned pay: 1;
          }workers;'
    上例的结构定义了关于一个工从的信息。其中有两个位结构成员, 每个位结
构成员只有一位, 因此只占一个字节但保存了两个信息, 该字节中第一位表示工
人的状态, 第二位表示工资是否已发放。由此可见使用位结构可以节省存贮空间。
 
 
                             返回目录
       }
                            合(union)
    1. 联合说明和联合变量定义
    联合也是一种新的数据类型, 它是一种特殊形式的变量。
    联合说明和联合变量定义与结构十分相似。其形式为:
     union 联合名{
          数据类型 成员名;
          数据类型 成员名;
          ...
     } 联合变量名;
    联合表示几个变量公用一个内存位置, 在不同的时间保存不同的数据类型
和不同长度的变量。
    下例表示说明一个联合a_bc:
     union a_bc{
          int i;
          char mm;
     };
    再用已说明的联合可定义联合变量。
    例如用上面说明的联合定义一个名为lgc的联合变量, 可写成:
      union a_bc lgc;
    在联合变量lgc中, 整型量i和字符mm公用同一内存位置。
    当一个联合被说明时, 编译程序自动地产生一个变量, 其长度为联合中最大
的变量长度。
    联合访问其成员的方法与结构相同。同样联合变量也可以定义成数组或指针,
但定义为指针时, 也要用"->"符号, 此时联合访问成员可表示成:
     联合名->成员名
    另外, 联合既可以出现在结构内, 它的成员也可以是结构。
    例如:
     struct{
          int age;
          char *addr;
          union{
               int i;
               char *ch;
          }x;
     }y[10];
    若要访问结构变量y[1]中联合x的成员i, 可以写成:
      y[1].x.i;
    若要访问结构变量y[2]中联合x的字符串指针ch的第一个字符可写成:
      *y[2].x.ch;
    若写成"y[2].x.*ch;"是错误的。
 
    2. 结构和联合的区别
    结构和联合有下列区别:
    1. 结构和联合都是由多个不同的数据类型成员组成, 但在任何同一时刻,
联合中只存放了一个被选中的成员, 而结构的所有成员都存在。
    2. 对于联合的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存
在了, 而对于结构的不同成员赋值是互不影响的。
    下面举一个例了来加对深联合的理解。
    4:
     main()
     {
          union{                   /*定义一个联合*/
               int i;
               struct{             /*在联合中定义一个结构*/
                    char first;
                    char second;
               }half;
          }number;
          number.i=0x4241;         /*联合成员赋值*/
          printf("%c%c/n", number.half.first, mumber.half.second);
          number.half.first='a';   /*联合中结构成员赋值*/
          number.half.second='b';
          printf("%x/n", number.i);
          getch();
     }
    输出结果为:
     AB
     6261
    从上例结果可以看出: 当给i赋值后, 其低八位也就是first和second的值;
当给first和second赋字符后, 这两个字符的ASCII码也将作为i 的低八位和高八
位。
                           举(enum)
 
    枚举是一个被命名的整型常数的集合, 枚举在日常生活中很常见。
    例如表示星期的SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY, 就是一个枚举。
    枚举的说明与结构和联合相似, 其形式为:
          enum 枚举名{
               标识符[=整型常数],
               标识符[=整型常数],
               ...
               标识符[=整型常数],
          } 枚举变量;
    如果枚举没有初始化, 即省掉"=整型常数"时, 则从第一个标识符开始, 顺
次赋给标识符0, 1, 2, ...。但当枚举中的某个成员赋值后, 其后的成员按依次
1的规则确定其值。
    例如下列枚举说明后, x1, x2, x3, x4的值分别为0, 1, 2, 3。
     enum string{x1, x2, x3, x4}x;
    当定义改变成:
      enum string
      {
          x1,
          x2=0,
          x3=50,
          x4,
      }x;
    x1=0, x2=0, x3=50, x4=51
    注意:
    1. 枚举中每个成员(标识符)结束符是",", 不是";", 最后一个成员可省略
","。
    2. 初始化时可以赋负数, 以后的标识符仍依次加1。
    3. 枚举变量只能取枚举说明结构中的某个标识符常量。
    例如:
      enum string
      {
          x1=5,
          x2,
          x3,
          x4,
      };
     enum strig x=x3;
    此时, 枚举变量x实际上是7。
 
 
 
                            
 
    类型说明的格式为:
     typedef 类型 定义名;
    类型说明只定义了一个数据类型的新名字而不是定义一种新的数据类型。这
里类型是Turbo C许可的任何一种数据类型。定义名表示这个类型的新名字。
    例如: 用下面语句定义整型数的新名字:
     typedef int SIGNED_INT;
    使用说明后, SIGNED_INT就成为int的同义词了, 此时可以用SIGNED_INT 定
义整型变量。
    例如: SIGNED_INT i, j;(与int i, j等效)。
    long SIGNED_INT i, j; 是非法的。
    typedef同样可用来说明结构、联合以及枚举。
    说明一个结构的格式为:
      typedef struct{
          数据类型 成员名;
          数据类型 成员名;
          ...
        } 结构名;
    此时可直接用结构名定义结构变量了。例如:
     typedef struct{
          char name[8];
          int class;
          char subclass[6];
          float math, phys, chem, engl, biol;
      } student;
      student Liuqi;
    Liuqi被定义为结构数组和结构指针。
    在第二节讲过的文件操作中, 用到的FILE就是一个已被说明的结构, 其说明
如下:
     typedef struct
     {
          short level;
          unsigned flags;
          char fd;
          unsigned char hold;
          short bsize;
          unsigned char *buffer;
          unsigned char *curp;
          unsigned istemp;
          short token;
     } FILE
    这个结构说明已包含在stdio.h中, 用户只要直接用FILE 定义文件指针变量
就可以。事实上, 引入类型说明的目的并非为了方便, 而是为了便于程序的移植。
 
 
 
                 处 理 指 令
 
    ANSI的标准规定, 预处理指令主要包括:
     #define
     #error
     #if
     #else
     #elif
     #endif
     #ifdef
     #ifndef
     #undef
     #line
     #pragma
    由上述指令可以看出, 每个预处理指令均带有符号"#"。下面只介绍一些常
用指令。
    1. #define 指令
    #define指令是一个宏定义指令, 定义的一般形式是:
     #define 宏替换名字符串(或数值)
    #define指令定义后, 在程序中每次遇到该宏替换名时就用所定义的字符
(或数值)代替它。
    例如: 可用下面语句定义TRUE表示数值1, FALSE表示0。
     #define TRUE 1
     #define FALSE 0
    一旦在源程序中使用了TRUE和FALSE, 编译时会自动的用1和0代替。
    注意:
    1. 在宏定义语名后没有";"
    2. Turbo C程序中习惯上用大写字符作为宏替换名, 而且常放在程序开头。
    3. 宏定义还有一个特点, 就是宏替换名可以带有形式参数, 在程序中用到
, 实际参数会代替这些形式参数。
    例如:
     #define MAX(x, y) (x>y)?x:y
     main()
     {
          int i=10, j=15;
          printf("The Maxmum is %d", MAX(i, j);
     }
    上例宏定义语句的含义是用宏替换名MAX(x, y)代替x, y中较大者, 同样也
可定义:
     #define MIN(x, y) (x<y)?x:y
    表示用宏替换名MIN(x, y)代替x, y中较小者。
 
    2. #error指令
    该指令用于程序的调试, 当编译中遇到#error指令就停止编译。其一般形式
:
     #error 出错信息
    出错信息不加引号, 当编译器遇到这个指令时, 显示下列信息并停止编译。
      Fatal: filename linename error directive
 
    3. #include 指令
       #include 指令的作用是指示编译器将该指令所指出的另一个源文件嵌入
#include指令所在的程序中, 文件应使用双引号或尖括号括起来。Turbo C 库函
数的头文件一般用#include指令在程序开关说明。
    例如:
     #include <stdio.h>
    程序也允许嵌入其它文件, 例如:
     main()
     {
          #include <help.c>
     }
    其中help.c为另一个文件, 内容可为
       printf("Glad to meet you here!");
    上例编译时将按集成开发环境的Options/Directories/Include directories
中指定的包含文件路径查找被嵌入文件。
 
    4. #if#else、#endif指令
    #if#els和#endif指令为条件编择指令, 它的一般形式为:
     #if 常数表达式
          语句段;
     #else
          语句段;
     #endif
    上述结构的含义是: 若#if指令后的常数表达式为真, 则编译#if到#else 之
间的程序段; 否则编译#else到#endif之间的程序段。
    例如:
     #define MAX 200
     main()
     {
          #if MAX>999
               printf("compiled for bigger/n");
          #else
               printf("compiled for small/n");
          #endif
     }
 
    5. #undef指令
    #undef指令用来删除事先定义的宏定义, 其一般形式为:
     #undef 宏替换名
    例如:
      #define TRUE 1
       ...
      #undef TURE
    #undef主要用来使宏替换名只限定在需要使用它们的程序段中。
                            函数
 
    C程序是由一组或是变量或是函数的外部对象组成的。 函数是一个自我包含的
完成一定相关功能的执行代码段。我们可以把函数看成一个"黑盒子", 你只要将数
据送进去就能得到结果, 而函数内部究竟是如何工作的的, 外部程序是不知道的。
外部程序所知道的仅限于输入给函数什么以及函数输出什么。函数提供了编制程序
的手段, 使之容易读、写、理解、排除错误、修改和维护。
    C程序中函数的数目实际上是不限的, 如果说有什么限制的话, 那就是, 一个C
程序中必须至少有一个函数, 而且其中必须有一个并且仅有一个以main为名, 这个
函数称为主函数, 整个程序从这个主函数开始执行。
    C 语言程序鼓励和提倡人们把一个大问题划分成一个个子问题, 对应于解决一
个子问题编制一个函数, 因此, C 语言程序一般是由大量的小函数而不是由少量大
函数构成的, 即所谓"小函数构成大程序"。这样的好处是让各部分相互充分独立,
并且任务单一。因而这些充分独立的小模块也可以作为一种固定规格的小"构件",
用来构成新的大程序。
    C语言的一个主要特点是可以建立库函数。Turbo C2.0提供的运行程序库有400
多个函数, 每个函数都完成一定的功能, 可由用户随意调用。这些函数总的分为输
入输出函数、数学函数、字符串和内存函数、与BIOS和DOS有关的函数、 字符屏幕
和图形功能函数、过程控制函数、目录函数等。对这些库函数应熟悉其功能, 只有
这样才可省去很多不必要的工作。
    本教程后半部分专门介绍Turbo C2.0的库函数, 并对每个函数都给出例程, 读
者可以将自已需要的部分以块的方式定义, 然后将此块写入文件, 这样就可以在进
Turbo C2.0集成开发环境后, 直接调用此程序, 连接, 运行, 观察结果, 以加深
对该函数的理解。
    用户编制Turbo C语言源程序, 就是利用Turbo C的库函数。可以把所有使用的
库函数放在一个庞大的主函数里, 也可以按不同功能设计成一个个用户函数而被其
它函数调用。Turbo C2.0建议用户使用后者, 当用户编制了一些较常用的函数时,
只要将其存在函数库里, 在以后的编程中可被方便的调用而不需要再去编译它们。
连接时将会自动从相应的库中装配成所需程序。
 
    1. 函数的说明与定义
    Turbo C2.0中所有函数与变量一样在使用之前必须说明。所谓说明是指说明函
数是什么类型的函数, 一般库函数的说明都包含在相应的头文件<*.h>中, 例如标
准输入输出函数包含在stdio.h中, 非标准输入输出函数包含在io.h中, 以后在使
用库函数时必须先知道该函数包含在什么样的头文件中, 在程序的开头用#include
<*.h>或#include"*.h"说明。只有这样程序在编译, 连接时Turbo C 才知道它是提
供的库函数, 否则, 将认为是用户自己编写的函数而不能装配。
 
    1.1 函数说明
 
    1. 经典方式
         其形式为: 函数类型   函数名();
    2. ANSI 规定方式
         其形式为: 函数类型 函数名(数据类型 形式参数, 数据类型 形式
                    参数, ......);
    其中: 函数类型是该函数返回值的数据类型, 可以是以前介绍的整型(int),
长整型(long), 字符型(char), 单浮点型(float), 双浮点型(double)以及无值型
(void), 也可以是指针, 包括结构指针。无值型表示函数没有返回值。
    函数名为Turbo C2.0的标识符, 小括号中的内容为该函数的形式参数说明。可
以只有数据类型而没有形式参数, 也可以两者都有。对于经典的函数说明没有参数
信息。如:
     int putlll(int x,int y,int z,int color,char *p)/*说明一个整型函数*/
     char *name(void);               /*说明一个字符串指什函数*/
     void student(int n, char *str); /*说明一个不返回值的函数*/
     float calculate();              /*说明一个浮点型函数*/
    注意: 如果一个函数没有说明就被调用, 编译程序并不认为出错, 而将此函数
默认为整型(int)函数。因此当一个函数返回其它类型, 又没有事先说明, 编译时
将会出错。
 
    1.2 函数定义
 
    函数定义就是确定该函数完成什么功能以及怎么运行, 相当于其它语言的一个
子程序。Turbo C2.0对函数的定义采用ANSI规定的方式。即:
       函数类型 函数名(数据类型形式参数; 数据类型 形式参数...)
      {
          函数体;
       }
    其中函数类型和形式参数的数据类型为Turbo C2.0的基本数据类型。函数体为
Turbo C2.0提供的库函数和语句以及其它用户自定义函数调用语句的组合, 并包括
在一对花括号"{"和"}"中。
    需要指出的是一个程序必须有一个主函数, 其它用户定义的子函数可以是任意
多个, 这些函数的位置也没有什么限制, 可以在main()函数前, 也可以在其后。
Turbo C2.0将所有函数都被认为是全局性的。而且是外部的, 即可以被另一个文件
中的任何一个函数调用。
 
    2 函数的调用
 
    2.1 函数的简单调用
    Turbo C2.0调用函数时直接使用函数名和实参的方法, 也就是将要赋给被调用
函数的参量, 按该函数说明的参数形式传递过去, 然后进入子函数运行, 运行结束
后再按子函数规定的数据类型返回一个值给调用函数。使用Turbo C2.0的库函数就
是函数简单调用的方法。举例说明如下:
    1:
     #include<stdio.h>
     int maxmum(int x, int y, int z);   /*说明一个用户自定义函数*/
     int main()
     {
          int i, j, k;
          printf("i, j, k=?/n");
          scanf("%4d%4d%4d", &i, &j, &k);
          maxmum(i, j, k);
          getch();
          return 0;
     }
 
     maxmum(int x, int y, int z)
     {
          int max;
          max=x>y?x:y;
          max=max>z?max:z;
          printf("The maxmum value of the 3 data is %d/n", max);
     }
 
    2.2 函数参数传递
 
    一、调用函数向被调用函数以形式参数传递
    用户编写的函数一般在对其说明和定义时就规定了形式参数类型, 因此调用这
些函数时参量必须与子函数中形式参数的数据类型、顺序和数量完全相同, 否则在
调用中将会出错, 得到意想不到的结果。
    注意:
    当数组作为形式参数向被调用函数传递时, 只传递数组的地址, 而不是将整个
数组元素都复制到函数中去, 即用数组名作为实参调用子函数, 调用时指向该数组
第一个元素的指针就被传递给子函数。因为在Turbo C2.0中, 没有下标的数组名就
是一个指向该数组第一个元素的指针。当然数组变量的类型在两个函数中必须相同。
    用下述方法传递数组形参。
    2:
     #include<stdio.h>
     void disp(int *n);
     int main()
     {
          int m[10], i;
          for(i=0; i<10; i++)
            m[i]=i;
          disp(m);       /*按指针方式传递数组*/
          getch();
          return 0;
     }
     void disp(int *n)
     {
          int j;
          for(j=0; j<10; j++)
            printf("%3d", *(n++));
          printf("/n");
     }
    另外, 当传递数组的某个元素时, 数组元素作为实参, 此时按使用其它简单变
量的方法使用数组元素。例2按传递数组元素的方法传递时变为:
     #include<stdio.h>
     void disp(int n);
     int main()
     {
          int m[10], i;
          for(i=0; i<10; i++){
            m[i]=i;
            disp(m[i]); /*逐个传递数组元素*/
          }
          getch();
          return 0;
     }
     void disp(int n)
     {
          printf("%3d/t");
     }
这时一次只传递了数组的一个元素。
 
    二、被调用函数向调用函数返回值
 
    一般使用return语句由被调用函数向调用函数返回值, 该语句有下列用途:
    1. 它能立即从所在的函数中退出, 返回到调用它的程序中去。
    2. 返回一个值给调用它的函数。
    有两种方法可以终止子函数运行并返回到调用它的函数中: 一是执行到函数的
最后一条语句后返回; 一是执行到语句return时返回。前者当子函数执行完后仅返
回给调用函数一个0。若要返回一个值, 就必须用return语句。只需在return 语句
中指定返回的值即可。例1返回最大值时变为:
     3:
     #include<stdio.h>
     int maxmum(int x, int y, int z);   /*说明一个用户自定义函数*/
     int main()
     {
          int i, j, k, max;
          printf("i, j, k=?/n");
          scanf("%4d%4d%4d", &i, &j, &k);
          max=maxmum(i, j, k);     /*调用子函数, 并将返回值赋给max*/
          printf("The maxmum value is %d/n", max);
          getch();
          return 0;
     }
 
     maxmum(int x, int y, int z)
     {
          int max;
          max=x>y?x:y;        /*求最大值*/
          max=max>z?max:z;
          return(max);        /*返回最大值*/
     }
    return语句可以向调用函数返回值, 但这种方法只能返回一个参数, 在许多情
况下要返回多个参数, 这是用return语句就不能满足要求。Turob C2.0提供了另一
种参数传递的方法, 就是调用函数向被调用函数传递的形式参数不是传递变量本身,
而是传递变量的地址, 当子函数中向相应的地址写入不同的数值之后, 也就改变了
调用函数中相应变量的值, 从而达到了返回多个变量的目的。
     4:
     #include<stdio.h>
     void subfun(int *m, int *n); /*说明子函数*/
     int main()
     {
          int i, j;
          printf("i, j=?/n");
          scanf("%d, %d", &i, &j); /*从键盘输入2个整数*/
          printf("In main before calling/n"/*输出此2数及其乘积*/
                 "i=%-4d j=%-4d i*j=%-4d/n", i, j, i*j);
          subfun(&i, &j);          /*以传送地址的方式调用子函数*/
          printf("In main after calling/n"/*调用子函数后输出变量值*/
                 "i=%-4d j=%-4d i*j=%-4d/n", i, j, i*j);
          getch();
          return 0;
     }
     void subfun(int *m, int *n)
     {
          *m=*m+2;
          *j=*i-*j;
         printf("In subfun after calling/n" /*子函数中输出变量值*/
                 "i=%-4d j=%-4d i*j=%-4d/n", *i, *j, *i**j);
      }
 
    上例中, *i**j表示指针i和j所指的两个整型数*i和*j之乘积。
    另外, return语句也可以返回一个指针, 举例如下。
    下例中先等待输入一字符串, 再等待输入要查找的字符, 然后调用match() 函
数在字符串中查找该字符。若有相同字符, 则返回一个指向该字符串中这一位置的
指针, 如果没有找到, 则返回一个空(NULL)指针。
    5:
     #include<stdio.h>
     char *match(char c, char *s);
     int main()
     {
          char s[40], c, *str;
          str=malloc(40);          /*为字符串指什分配内存空间*/
          printf("Please input character string:");
          gets(s);                 /*键盘输入字符串*/
          printf("Please input one character:");
          c=getche();              /*键盘输入字符*/
          str=match(c, s);         /*调用子函数*/
          putchar('/n');
          puts(str);               /*输出子函数返回的指针所指的字符串*/
          getch();
          return 0;
     }
     char *match(char c, char *s)
     {
          int i=0;
          while(c!=s[i]&&s[i]!='/n')/*找字符串中指定的字符*/
               i++;
          return(&s[i]);           /*返回所找字符的地址*/
     }
 
 
    三、用全程变量实现参数互传
    以上两种办法可以在调用函数和被调用函数间传递参数, 但使用不太方便。如
果将所要传递的参数定义为全程变量, 可使变量在整个程序中对所有函数都可见。
这样相当于在调用函数和被调用函数之间实现了参数的传递和返回。这也是实际中
经常使用的方法, 但定义全程变量势必长久地占用了内存。因此, 全程变量的数目
受到限制, 特别对于较大的数组更是如此。当然对于绝大多数程序内存都是够用的。
    6:
     #incluide<stdio.h>
     void disp(void);
     int m[10];          /*定义全程变量*/
     int main()
     {
          int i;
          printf("In main before calling/n");
          for(i=0; i<10; i++){
            m[i]=i;
            printf("%3d", m[i]);   /*输出调用子函数前数组的值*/
          }
          disp();                  /*调用子函数*/
          printf("/nIn main after calling/n");
          for(i=0; i<10; i++)
            printf("%3d", m[i]);   /*输出调用子函数后数组的值*/
          getch();
          return 0;
     }
     void disp(void)
     {
          int j;
          printf("In subfunc after calling/n");/*子函数中输出数组的值*/
          for (j=0; i<10; j++){
               m[j]=m[j]*10;
               printf("%3d", m[i]);
          }
     }
 
 
    2.3 函数的递归调用
    Turbo C2.0允许函数自己调用自己, 即函数的递归调用, 递归调用可以使程序
简洁、代码紧凑, 但要牺牲内存空间作处理时的堆栈。
    如要求一个n!(n的阶乘)的值可用下面递归调用:
    8:
      #include<stdio.h>
      unsigned ling mul(int n);
      int main()
     {
          int m;
          puts("Calculate n! n=?/n");
          scanf("%d", &m);         /*键盘输入数据*/
          printf("%d!=%ld/n", m, mul(m));/*调用子程序计算并输出*/
          getch();
          retun 0;
      }
     unsigned long mul(int n)
     {
          unsigned long p;
          if(n>1)
               p=n*mul(n-1);       /*递归调用计算n!*/
          else
               p=1L;
          return(p);               /*返回结果*/
     }
运行结果:
          calculate n! n=?
输入5时结果为:
          5!=120
 
    3. 函数作用范围
 
    Turbo C2.0中每个函数都是独立的代码块, 函数代码归该函数所有, 除了对函
数的调用以外, 其它任何函数中的任何语句都不能访问它。例如使用跳转语句goto
就不能从一个函数跳进其它函数内部。除非使用全程变量, 否则一个函数内部定义
的程序代码和数据, 不会与另一个函数内的程序代码和数据相互影响。
    Turbo C2.0中所有函数的作用域都处于同一嵌套程度, 即不能在一个函数内再
说明或定义另一个函数。
    Turbo C2.0中一个函数对其它子函数的调用是全程的, 即是函数在不同的文件
, 也不必附加任何说明语句而被另一函数调用, 也就是说一个函数对于整个程序
都是可见的。
 
    4. 函数的变量作用域
    Turbo C2.0中, 变是可以在各个层次的子程序中加以说明, 也就是说, 在任
何函数中, 变量说明有只允许在一个函数体的开头处说明, 而且允许变量的说明(
包括初始化)跟在一个复合语句的左花括号的后面, 直到配对的右花括号为止。它
的作用域仅在这对花括号内, 当程序执行到出花括号时, 它将不复存在。当然, 内
层中的变量即使与外层中的变量名字相同, 它们之间也是没有关系的。
    9.
     #include<stdio.h>
     int i=10;
     int main()
     {
          int i=1;
          printf("%d/t, i);
          {
               int i=2;
               pritnf("%d/t", i);
               {
                    extern i;
                    i+=1;
                    printf("%d/t", i);
               }
               printf("%d/t", ++i);
          }
          printf("%d/n", ++i);
          return 0;
     }
 运行结果为
     1    2    11   3    2
 从程序运行的结果不难看出程序中各变量之间的关系, 以及各个变量的作用域。
 
二、函数篇 
                    字符屏幕函数
 
    Turbo C2.0的字符屏幕函数主要包括文本窗口大小的设定、窗口颜色的设置、
窗口文本的清除和输入输出等函数。
 
    1.文本窗口的定义
    Turbo C2.0默认定义的文本窗口为整个屏幕, 共有80列(或40列)25行的文本
单元, 每个单元包括一个字符和一个属性, 字符即ASCII 码字符, 属性规定该字
符的颜色和强度。
    Turbo C2.0可以定义屏幕上的一个矩形域作为窗口, 使用window()函数定义。
窗口定义之后, 用有关窗口的输入输出函数就可以只在此窗口内进行操作而不超
出窗口的边界。
    window()函数的调用格式为:
     void window(int left, int top, int right, int bottom);
    该函数的原型在conio.h 中 (关于文本窗口的所有函数其头文件均为conio.h,
后面不再说明)。 函数中形式参数(int left, int top)是窗口左上角的坐标,
(int right, int bottom)是窗口的右下角坐标, 其中(left, top)和(right,
bottom) 是相对于整个屏幕而言的。 Turbo C 2.0规定整个屏幕的左上角坐标为
(1, 1), 右下角坐标为(80, 25)。并规定沿水平方向为 X轴, 方向朝右; 沿垂直
方向为 Y轴, 方向朝下。若window()函数中的坐标超过了屏幕坐标的界限, 则窗
口的定义就失去了意义, 也就是说定义将不起作用, 但程序编译链接时并不出错。
    另外, 一个屏幕可以定义多个窗口, 但现行窗口只能有一个(因为DOS为单任
务操作系统), 当需要用另一窗口时, 可将定义该窗口的window() 函数再调用一
, 此时该窗口便成为现行窗口了。
    如要定义一个窗口左上角在屏幕(20, 5)处, 大小为30列15行的窗口可写成:
     window(20, 5, 50, 25);
 
    2. 文本窗口颜色的设置
    文本窗口颜色的设置包括背景颜色的设置和字符颜色的设置, 使用的函数及
其调用格式为:
    设置背景颜色: void textbackground(int color);
    设置字符颜色: void textcolor(int color);
    有关颜色的定义见表1。
                  1. 有关颜色的定义
━━━━━━━━━━━━━━━━━━━━━━━━━━━
 符号常数         数值      含义         字符或背景
───────────────────────────
 BLACK             0                   两者均可
 BLUE              1                   两者均可
 GREEN             2         绿          两者均可
 CYAN              3                   两者均可
 RED               4                   两者均可
 MAGENTA           5        洋红         两者均可
 BROWN             6                   两者均可
 LIGHTGRAY         7        淡灰         两者均可
 DARKGRAY          8        深灰         只用于字符
 LIGHTBLUE         9        淡兰         只用于字符
 LIGHTGREEN        10       淡绿         只用于字符
 LIGHTCYAN         11       淡青         只用于字符
 LIGHTRED          12       淡红         只用于字符
 LIGHTMAGENTA      13       淡洋红       只用于字符
 YELLOW            14                  只用于字符
 WHITE             15                  只用于字符
 BLINK             128      闪烁         只用于字符
━━━━━━━━━━━━━━━━━━━━━━━━━━━
    上表中的符号常数与相应的数值等价, 二者可以互换。例如设定兰色背景可
以使用textbackground(1), 也可以使用textbackground(BLUE), 两者没有任何
区别, 只不过后者比较容易记忆, 一看就知道是兰色。
    Turbo C另外还提供了一个函数, 可以同时设置文本的字符和背景颜色, 这
个函数的调用格式为:
     void textattr(int attr);
    其中: attr的值表示颜色形式编码的信息, 每一位代表的含义如下:
             7   6   5   4      3   2   1   0
               B   b   b   b      c   c   c   c
                ┕━━━┙     ┖─────┘
              闪烁 背景颜色         字符颜色
    字节低四位cccc设置字符颜色(0到15), 4~6三位bbb设置背景颜色(0到7),
7位B设置字符是否闪烁。假如要设置一个兰底黄字, 定义方法如下:
          textattr(YELLOW+(BLUE<<4));
    若再要求字符闪烁, 则定义变为:
          textattr(128+YELLOW+(BLUE<<4);
    注意:
      (1) 对于背景只有0 到7 共八种颜色, 若取大于7 小于15的数, 则代表的
颜色与减 7后的值对应的颜色相同。
      (2) textbackground()和textcolor() 函数设置了窗口的背景与字符颜
色后, 在没有用clrscr()函数清除窗口之前, 颜色不会改变,   直到使用了函数
clrscr(), 整个窗口和随后输出到窗口中的文本字符才会变成新颜色。
      (3) textattr()函数时背景颜色应左移4位, 才能使3位背景颜色移到正
确位置。
    下面这个程序使用了关于窗口大小的定义、颜色的设置等函数, 在一个屏幕
上不同位置定义了7个窗口, 其背景色分别使用了7种不同的颜色。
    1.:
      #include <stdio.h>
      #include <conio.h>
      main()
     {
          int i;
          textbackground(0);            /* 设置屏幕背景色 */
          clrscr();                     /* 清除文本屏幕 */
          for(i=1; i<8; i++)
            {
               window(10+i*5, 5+i, 30+i*5, 15+i); /* 定义文本窗口 */
               textbackground(i);        /* 定义窗口背景色 */
               clrscr();                 /* 清除窗口 */
             }
          getch();
     }
 
    3. 窗口内文本的输入输出函数
 
    一、窗口内文本的输出函数
          int cprintf("<格式化字符串>", <变量表>);
          int cputs(char *string);
          int putch(int ch);
    cprintf()函数输出一个格式化的字符串或数值到窗口中。它与printf() 函
数的用法完全一样, 区别在于cprintf()函数的输出受窗口限制, 而printf() 函
数的输出为整个屏幕。
    cputs()函数输出一个字符串到屏幕上, 它与puts()函数用法完全一样, 只
是受窗口大小的限制。
    putch()函数输出一个字符到窗口内。
    注意:
     (1) 使用以上几种函数, 当输出超出窗口的右边界时会自动转到下一行的
开始处继续输出。当窗口内填满内容仍没有结束输出时, 窗口屏幕将会自动逐行
上卷直到输出结束为止。
 
    二、窗口内文本的输入函数
        int getche(void);
    该函数在前面已经讲过, 需要说明的是, getche()函数从键盘上获得一个字
, 在屏幕上显示的时候, 如果字符超过了窗口右边界, 则会被自动转移到下一
行的开始位置。
   下面这个程序给例1.中加入了一些文本的输出函数。
   2.:
      #include <stdio.h>
      #include <conio.h>
      int main()
     {
          int i;
          char *c[]={"BLACK",   "BLUE",   "GREEN",   "CYAN",   "RED",
                     "MAGENTA", "BROWN", "LIGHTGRAY"};
          textbackground(0);            /* 设置屏幕背景色 */
          clrscr();                     /* 清除文本屏幕 */
          for(i=1; i<8; i++)
            {
               window(10+i*5, 5+i, 30+i*5, 15+i); /* 定义文本窗口 */
               textbackground(i);        /* 定义窗口背景色 */
               clrscr();                 /* 清除窗口 */
             }
          getch();
          return 0;
     }
 
    4. 有关屏幕操作的函数
 
    void clrscr(void);   清除当前窗口中的文本内容, 并把光标定位在窗口
                         的左上角(1, 1)处。
    void clreol(void);   清除当前窗口中从光标位置到行尾的所有字符, 光
                         标位置不变。
    void gotoxy(x, y);   该函数很有用, 它用来定位光标在当前窗口中的位
                         置。这里x, y是指光标要定位处的坐标(相对于窗口
                         而言), 当x, y超出了窗口的大小时, 该函数就不起
                         作用了。
 
     int gettext(int xl, int yl, int x2, int y2, void *buffer);
     int puttext(int x1, int y1, int x2, int y2, void *buffer);
    gettext()函数是将屏幕上指定的矩形区域内文本内容存入buffer 指针指向
的一个内存空间。内存的大小用下式计算:
     所用字节大小=行数*列数*2
其中:
     行数=y2-y1+1        列数=x2-x1+1
    puttext()函数则是将gettext()函数存入内存buffer中的文字内容拷贝到屏
幕上指定的位置。
    int movetext(int x1, int x2, int y2, int x3, int y3);
    movetext()函数将屏幕上左上角为(x1, y1), 右下角为(x2, y2)的一矩形窗
口内的文本内容拷贝到左上角为(x3, y3)的新的位置。该函数的坐标也是相对于
整个屏幕而言的。
    注意:
    1. gettext()函数和puttext()函数中的坐标是对整个屏幕而言的, 即是屏
幕的绝对坐标, 而不是相对窗口的坐标。
    2. movetext()函数是拷贝而不是移动窗口区域内容, 即使用该函数后, 原
位置区域的文本内容仍然存在。
 
    3.
     include <conio.h>
     main()
     {
          int i;
          char *f[]={"Load    F3", "Pick Alt-F3", "New    ",
                     "Save    F2", "Write to    ", "Directory",
                     "Change dir", "Os shee    ", "Quit Alt-X"};
          char buf[9*14*2];
          clrscr();
          textcolor(YELLOW);
          textbackground(BLUE);
          clrscr();
          gettext(10, 2, 24, 11, buf);
          window(10, 2, 24, 11);
          textbackground(RED);
          textcolor(YELLOW);
          clrscr();
          for(i=0; i<9; i++)
          {
               gotoxy(1, i++);
               cprintf("%s", f[i]);
          }
          getch();
          movetext(10, 2, 24, 11, 40, 10);
          puttext(10, 2, 24, 11, buf);
          getch();
     }
    下面再介绍一些函数:
     void highvideo(void);    设置显示器高亮度显示字符。
     void lowvideo(void);     设置显示器低亮度显示字符。
     void normvideo(void);    使显示器返回到程序运行前的显示方式。
     int wherex(void);        这两个函数返回当前窗口下光标的x, y坐标。
     int wherey(void);
 
 
                         图形函数
    Turbo C提供了非常丰富的图形函数, 所有图形函数的原型均在graphics. h
, 本节主要介绍图形模式的初始化、独立图形程序的建立、基本图形功能、图
形窗口以及图形模式下的文本输出等函数。另外, 使用图形函数时要确保有显示
器图形驱动程序*BGI, 同时将集成开发环境Options/Linker中的Graphics lib选
on, 只有这样才能保证正确使用图形函数。
    1. 图形模式的初始化
    不同的显示器适配器有不同的图形分辨率。即是同一显示器适配器, 在不同
模式下也有不同分辨率。因此, 在屏幕作图之前, 必须根据显示器适配器种类将
显示器设置成为某种图形模式, 在未设置图形模式之前, 微机系统默认屏幕为文
本模式(80列, 25行字符模式), 此时所有图形函数均不能工作。设置屏幕为图形
模式, 可用下列图形初始化函数:
     void far initgraph(int far *gdriver, int far *gmode, char *path);
    其中gdriver和gmode分别表示图形驱动器和模式, path是指图形驱动程序所
在的目录路径。有关图形驱动器、图形模式的符号常数及对应的分辨率见表2。
    图形驱动程序由Turbo C出版商提供, 文件扩展名为.BGI。根据不同的图形
适配器有不同的图形驱动程序。例如对于EGA、 VGA 图形适配器就调用驱动程序
EGAVGA.BGI。
 
               2. 图形驱动器、模式的符号常数及数值
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
     图形驱动器(gdriver)          图形模式(gmode)
   ───────────     ───────────    色调 分辨率
    符号常数    数值           符号常数     数值
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    CGA          1            CGAC0           0          C0   320*200
                              CGAC1           1          C1   320*200
                              CGAC2           2          C2   320*200
                              CGAC3           3          C3   320*200
                              CGAHI           4          2 640*200
───────────────────────────────────
    MCGA         2            MCGAC0          0          C0   320*200
                              MCGAC1          1          C1   320*200
                              MCGAC2          2          C2   320*200
                              MCGAC3          3          C3   320*200
                              MCGAMED         4          2 640*200
                              MCGAHI          5          2 640*480
───────────────────────────────────
    EGA          3            EGALO           0         16 640*200
                              EGAHI           1         16 640*350
───────────────────────────────────
    EGA64        4            EGA64LO         0         16 640*200
                              EGA64HI         1          4 640*350
───────────────────────────────────
    EGAMON       5            EGAMONHI        0          2 640*350
───────────────────────────────────
    IBM8514      6            IBM8514LO       0        256 640*480
                              IBM8514HI       1        2561024*768
───────────────────────────────────
    HERC         7            HERCMONOHI      0          2 720*348
───────────────────────────────────
    ATT400       8            ATT400C0        0          C0   320*200
                              ATT400C1        1          C1   320*200
                              ATT400C2        2          C2   320*200
                              ATT400C3        3          C3   320*200
                              ATT400MED       4          2 320*200
                              ATT400HI        5          2 320*200
───────────────────────────────────
    VGA          9            VGALO           0         16 640*200
                              VGAMED          1         16 640*350
                              VGAHI           2         16 640*480
───────────────────────────────────
    PC3270       10           PC3270HI        0          2 720*350
───────────────────────────────────
    DETECT       0            用于硬件测试
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
    4. 使用图形初始化函数设置VGA高分辨率图形模式
     #include <graphics.h>
     int main()
     {
          int gdriver, gmode;
          gdriver=VGA;
          gmode=VGAHI;
          initgraph(&gdriver, &gmode, "c://tc");
          bar3d(100, 100, 300, 250, 50, 1);       /*画一长方体*/
          getch();
          closegraph();
          return 0;
     }
 
    有时编程者并不知道所用的图形显示器适配器种类, 或者需要将编写的程序
用于不同图形驱动器, Turbo C提供了一个自动检测显示器硬件的函数, 其调用
格式为:
     void far detectgraph(int *gdriver, *gmode);
   其中gdriver和gmode的意义与上面相同。
 
    5. 自动进行硬件测试后进行图形初始化
     #include <graphics.h>
     int main()
     {
          int gdriver, gmode;
          detectgraph(&gdriver, &gmode);     /*自动测试硬件*/
          printf("the graphics driver is %d, mode is %d/n", gdriver,
                 gmode);       /*输出测试结果*/
          getch();
          initgraph(&gdriver, &gmode, "c://tc");
                               /* 根据测试结果初始化图形*/
          bar3d(10, 10, 130, 250, 20, 1);
          getch();
          closegraph();
          return 0;
      }
 
    上例程序中先对图形显示器自动检测, 然后再用图形初始化函数进行初始化
设置, 但Turbo C提供了一种更简单的方法, 即用gdriver= DETECT 语句后再跟
initgraph()函数就行了。采用这种方法后, 上例可改为:
 
    6.
     #include <graphics.h>
     int main()
     {
          int gdriver=DETECT, gmode;
          initgraph(&gdriver, &gmode, "c://tc");
          bar3d(50, 50, 150, 30, 1);
          getch();
          closegraph();
          return 0;
     }
    另外, Turbo C提供了退出图形状态的函数closegraph(), 其调用格式为:
     void far closegraph(void);
   调用该函数后可退出图形状态而进入文本方式(Turbo C 默认方式), 并释放
用于保存图形驱动程序和字体的系统内存。
 
    2. 独立图形运行程序的建立
    Turbo C对于用initgraph()函数直接进行的图形初始化程序, 在编译和链接
时并没有将相应的驱动程序(*.BGI)装入到执行程序, 当程序进行到intitgraph()
语句时, 再从该函数中第三个形式参数char *path中所规定的路径中去找相应的
驱动程序。若没有驱动程序, 则在C:/TC中去找, 如C:/TC中仍没有或TC不存在,
将会出现错误:
     BGI Error: Graphics not initialized (use 'initgraph')
    因此, 为了使用方便, 应该建立一个不需要驱动程序就能独立运行的可执行
图形程序,Turbo C中规定用下述步骤(这里以EGA、VGA显示器为例):
    1. C:/TC子目录下输入命令:BGIOBJ EGAVGA
    此命令将驱动程序EGAVGA.BGI转换成EGAVGA.OBJ的目标文件。
    2. C:/TC子目录下输入命令:TLIB LIB/GRAPHICS.LIB+EGAVGA
    此命令的意思是将EGAVGA.OBJ的目标模块装到GRAPHICS.LIB库文件中。
    3. 在程序中initgraph()函数调用之前加上一句:
       registerbgidriver(EGAVGA_driver):
该函数告诉连接程序在连接时把EGAVGA的驱动程序装入到用户的执行程序中。
    经过上面处理,编译链接后的执行程序可在任何目录或其它兼容机上运行。
假设已作了前两个步骤,若再向例6中加 registerbgidriver()函数则变成:
    7:
     #include<stdio.h>
     #include<graphics.h>
     int main()
     {
         int gdriver=DETECT,gmode;
         registerbgidriver(EGAVGA_driver): / *建立独立图形运行程序 */
         initgraph( gdriver, gmode,"c://tc");
         bar3d(50,50,250,150,20,1);
         getch();
         closegraph();
         return 0;
     }
    上例编译链接后产生的执行程序可独立运行。
    如不初始化成EGA或CGA分辨率, 而想初始化为CGA分辨率, 则只需要将上述
步骤中有EGAVGA的地方用CGA代替即可。
 
    3.屏幕颜色的设置和清屏函数
    对于图形模式的屏幕颜色设置, 同样分为背景色的设置和前景色的设置。在
Turbo C中分别用下面两个函数。
    设置背景色:        void far setbkcolor( int color);
    设置作图色:        void far setcolor(int color);
    其中color 为图形方式下颜色的规定数值, 对EGA, VGA显示器适配器, 有关
颜色的符号常数及数值见下表所示。
                3 有关屏幕颜色的符号常数表
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 符号常数      数值     含义           符号常数      数值     含义
───────────────────────────────────
 BLACK          0       黑色           DARKGRAY       8       深灰
 BLUE           1       兰色           LIGHTBLUE      9       深兰
 GREEN          2       绿色           LIGHTGREEN     10      淡绿
 CYAN           3       青色           LIGHTCYAN      11      淡青
 RED            4       红色           LIGHTRED       12      淡红
 MAGENTA        5       洋红           LIGHTMAGENTA   13      淡洋红
 BROWN          6       棕色           YELLOW         14      黄色
 LIGHTGRAY      7       淡灰           WHITE          15      白色
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    对于CGA适配器, 背景色可以为表3中16种颜色的一种, 但前景色依赖于不同
的调色板。共有四种调色板, 每种调色板上有四种颜色可供选择。不同调色板所
对应的原色见表4。
               4 CGA调色板与颜色值表
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
       调色板                               颜色值
───────────       ──────────────────
 符号常数    数值              0         1         2         3
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
      C0       0              背景       绿               
      C1       1               背景              洋红      
      C2       2               背景      淡绿      淡红      
      C3       3               背景      淡青     淡洋红     
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
    清除图形屏幕内容使用清屏函数, 其调用格式如下:
     voide far cleardevice(void);
    有关颜色设置、清屏函数的使用请看例8。
    8:
     #include<stdio.h>
     #include<graphics.h>
     int main()
     {
          int gdriver, gmode, i;
          gdriver=DETECT;
          registerbgidriver(EGAVGA_DRIVER);/*建立独立图形运行程序*/
          initgraph(&gdriver, &gmode", "");/*图形初始化*/
          setbkcolor(0);                   /*设置图形背景*/
          cleardevice();
          for(i=0; i<=15; i++)
          {
            setcolor(i);                   /*设置不同作图色*/
            circle(320, 240, 20+i*10);     /*画半径不同的圆*/
            delay(100);                    /*延迟100毫秒*/
          }
          for(i=0; i<=15; i++)
          {
             setbkcolor(i);                /*设置不同背景色*/
             cleardevice();
             circle(320, 240, 20+i*10);
             delay(100);
          }
          closegraph();
          return 0;
     }
 
    另外, TURBO C也提供了几个获得现行颜色设置情况的函数。
    int far getbkcolor(void);      返回现行背景颜色值。
    int far getcolor(void);        返回现行作图颜色值。
    int far getmaxcolor(void);     返回最高可用的颜色值。
 
    4. 基本图形函数
    基本图形函数包括画点, 线以及其它一些基本图形的函数。本节对这些函数
作一全面的介绍。
 
    一、画点
    1. 画点函数
     void far putpixel(int x, int y, int color);
    该函数表示有指定的象元画一个按color所确定颜色的点。对于颜色color的
值可从表3中获得而对x, y是指图形象元的坐标。
    在图形模式下, 是按象元来定义坐标的。对VGA适配器, 它的最高分辨率为
640x480, 其中640为整个屏幕从左到右所有象元的个数, 480 为整个屏幕从上到
下所有象元的个数。屏幕的左上角坐标为(0, 0), 右下角坐标为(639, 479), 水
平方向从左到右为x轴正向, 垂直方向从上到下为y轴正向。TURBO C 的图形函数
都是相对于图形屏幕坐标, 即象元来说的。
    关于点的另外一个函数是:
     int far getpixel(int x, int y);
    它获得当前点(x, y)的颜色值。
 
    2. 有关坐标位置的函数
 
     int far getmaxx(void);
    返回x轴的最大值。
 
     int far getmaxy(void);
    返回y轴的最大值。
 
     int far getx(void);
    返回游标在x轴的位置。
 
     void far gety(void);
    返回游标有y轴的位置。
 
     void far moveto(int x, int y);
    移动游标到(x, y)点, 不是画点, 在移动过程中亦画点。
 
     void far moverel(int dx, int dy);
    移动游标从现行位置(x, y)移动到(x+dx, y+dy)的位置, 移动过程中不画点。
 
    二、画线
    1. 画线函数
    TURBO C提供了一系列画线函数, 下面分别叙述:
 
     void far line(int x0, int y0, int x1, int y1);
    画一条从点(x0, y0)到(x1, y1)的直线。
 
     void far lineto(int x, int y);
    画一作从现行游标到点(x, y)的直线。
 
     void far linerel(int dx, int dy);
    画一条从现行游标(x, y)到按相对增量确定的点(x+dx, y+dy)的直线。
 
     void far circle(int x, int y, int radius);
    (x, y)为圆心, radius为半径, 画一个圆。
 
     void far arc(int x, int y, int stangle, int endangle, int radius);
    (x, y)为圆心, radius为半径, 从stangle开始到endangle结束(用度表示)
画一段圆弧线。在TURBO C中规定x轴正向为0度, 逆时针方向旋转一周, 依次为
90, 180, 270和360度(其它有关函数也按此规定, 不再重述)。
 
     void ellipse(int x, int y, int stangle, int endangle, int xradius,
int yradius);
    (x, y)为中心, xradius, yradius为x轴和y轴半径, 从角stangle 开始到
endangle结束画一段椭圆线, 当stangle=0, endangle=360时, 画出一个完整的
椭圆。
 
     void far rectangle(int x1, int y1, int x2, inty2);
    (x1, y1)为左上角, (x2, y2)为右下角画一个矩形框。
 
     void far drawpoly(int numpoints, int far *polypoints);
     画一个顶点数为numpoints,   各顶点坐标由polypoints 给出的多边形。
polypoints整型数组必须至少有2倍顶点数个无素。每一个顶点的坐标都定义为x,
y, 并且x在前。值得注意的是当画一个封闭的多边形时, numpoints 的值取实际
多边形的顶点数加一, 并且数组polypoints中第一个和最后一个点的坐标相同。
    下面举一个用drawpoly()函数画箭头的例子。
    9:
     #include<stdlib.h>
     #include<graphics.h>
     int main()
     {
          int gdriver, gmode, i;
          int arw[16]={200, 102, 300, 102, 300, 107, 330,
                       100, 300, 93, 300, 98, 200, 98, 200, 102};
          gdriver=DETECT;
          registerbgidriver(EGAVGA_driver);
          initgraph(&gdriver, &gmode, "");
          setbkcolor(BLUE);
          cleardevice();
          setcolor(12);       /*设置作图颜色*/
          drawpoly(8, arw);   /*画一箭头*/
          getch();
          closegraph();
          return 0;
     }
 
    2. 设定线型函数
    在没有对线的特性进行设定之前, TURBO C用其默认值, 即一点宽的实线,
TURBO C也提供了可以改变线型的函数。线型包括:宽度和形状。其中宽度只有
两种选择: 一点宽和三点宽。而线的形状则有五种。下面介绍有关线型的设置函
数。
 
     void far setlinestyle(int linestyle,   unsigned upattern,   int
thickness);
    该函数用来设置线的有关信息, 其中linestyle是线形状的规定, 见表5。
          5. 有关线的形状(linestyle)
━━━━━━━━━━━━━━━━━━━━━━━━━
    符号常数             数值          含义
─────────────────────────
    SOLID_LINE             0           实线
    DOTTED_LINE            1           点线
    CENTER_LINE            2           中心线
    DASHED_LINE            3           点画线
    USERBIT_LINE           4           用户定义线
━━━━━━━━━━━━━━━━━━━━━━━━━
     thickness是线的宽度, 见表6。
 
          6. 有关线宽(thickness)
━━━━━━━━━━━━━━━━━━━━━━━━━
     符号常数            数值           含义
─────────────────────────
     NORM_WIDTH           1             一点宽
     THIC_WIDTH           3             三点宽
━━━━━━━━━━━━━━━━━━━━━━━━━
    对于upattern, 只有linestyle选USERBIT_LINE 时才有意义( 选其它线型,
uppattern取0即可)。此进uppattern的16位二进制数的每一位代表一个象元, 如
果那位为1, 则该象元打开, 否则该象元关闭。
 
     void far getlinesettings(struct linesettingstype far *lineinfo);
           该函数将有关线的信息存放到由lineinfo 指向的结构中,     表中
linesettingstype的结构如下:
          struct linesettingstype{
               int linestyle;
               unsigned upattern;
               int thickness;
          }
    例如下面两句程序可以读出当前线的特性
     struct linesettingstype *info;
     getlinesettings(info);
 
     void far setwritemode(int mode);
    该函数规定画线的方式。如果mode=0, 则表示画线时将所画位置的原来信息
覆盖了(这是TURBO C的默认方式)。如果mode=1, 则表示画线时用现在特性的线
与所画之处原有的线进行异或(XOR)操作, 实际上画出的线是原有线与现在规定
的线进行异或后的结果。因此, 当线的特性不变, 进行两次画线操作相当于没有
画线。
    有关线型设定和画线函数的例子如下所示。
    10.
     #include<stdlib.h>
     #include<graphics.h>
     int main()
     {
          int gdriver, gmode, i;
          gdriver=DETECT;
          registerbgidriver(EGAVGA_driver);
          initgraph(&gdriver, &gmode, "");
          setbkcolor(BLUE);
          cleardevice();
          setcolor(GREEN);
          circle(320, 240, 98);
          setlinestyle(0, 0, 3);   /*设置三点宽实线*/
          setcolor(2);
          rectangle(220, 140, 420, 340);
          setcolor(WHITE);
          setlinestyle(4, 0xaaaa, 1);   /*设置一点宽用户定义线*/
          line(220, 240, 420, 240);
          line(320, 140, 320, 340);
          getch();
          closegraph();
          return 0;
     }
 
    5. 封闭图形的填充
    填充就是用规定的颜色和图模填满一个封闭图形。
 
    一、先画轮廓再填充
    TURBO C提供了一些先画出基本图形轮廓, 再按规定图模和颜色填充整个封
闭图形的函数。在没有改变填充方式时, TURBO C以默认方式填充。 下面介绍这
些函数。
 
     void far bar(int x1, int y1, int x2, int y2);
    确定一个以(x1, y1)为左上角, (x2, y2)为右下角的矩形窗口, 再按规定图
模和颜色填充。
    说明: 此函数不画出边框, 所以填充色为边框。
 
    void far bar3d(int x1, int y1, int x2, int y2,   int depth,   int
topflag);
    topflag为非0时, 画出一个三维的长方体。当topflag为0时, 三维图形不
封顶, 实际上很少这样使用。
    说明: bar3d()函数中, 长方体第三维的方向不随任何参数而变, 即始终为
45度的方向。
 
     void far pieslice(int x, int y, int stangle, int endangle,   int
radius);
    画一个以(x, y)为圆心, radius为半径, stangle为起始角度, endangle 为
终止角度的扇形, 再按规定方式填充。当stangle=0, endangle=360 时变成一个
实心圆, 并在圆内从圆点沿X轴正向画一条半径。
 
     void far sector(int x, int y,   int stanle,   intendangle,   int
xradius, int yradius);
    画一个以(x, y)为圆心分别以xradius, yradius为x轴和y轴半径, stangle
为起始角, endangle为终止角的椭圆扇形, 再按规定方式填充。
 
    二、设定填充方式
    TURBO C有四个与填充方式有关的函数。下面分别介绍:
 
     void far setfillstyle(int pattern, int color);
    color的值是当前屏幕图形模式时颜色的有效值。pattern的值及与其等价的
符号常数如表7所示。
            7. 关于填充式样pattern的规定
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━
       符号常数          数值      含义
     ───────────────────────────
       EMPTY_FILL         0        以背景颜色填充
       SOLID_FILL         1        以实填充
       LINE_FILL          2        以直线填充
       LTSLASH_FILL       3        以斜线填充(阴影线)
       SLASH_FILL         4        以粗斜线填充(粗阴影线)
       BKSLASH_FILL       5        以粗反斜线填充(粗阴影线)
       LTBKSLASH_FILL     6        以反斜线填充(阴影线)
       HATCH_FILL         7        以直方网格填充
       XHATCH_FILL        8        以斜网格填充
       INTTERLEAVE_FILL   9        以间隔点填充
       WIDE_DOT_FILL      10       以稀疏点填充
       CLOSE_DOS_FILL     11       以密集点填充
       USER_FILL          12       以用户定义式样填充
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━
 
    USER_FILL(用户定义填充式样)以外, 其它填充式样均可由setfillstyle()
函数设置。当选用USER_FILL时, 该函数对填充图模和颜色不作任何改变。 之所
以定义USER_FILL主要因为在获得有关填充信息时用到此项。
    void far setfillpattern(char * upattern,int color);
    设置用户定义的填充图模的颜色以供对封闭图形填充。
    其中upattern是一个指向8个字节的指针。这8个字节定义了8x8点阵的图形。
每个字节的8位二进制数表示水平8点, 8个字节表示8行, 然后以此为模型向个封
闭区域填充。
    void far getfillpattern(char * upattern);
    该函数将用户定义的填充图模存入upattern指针指向的内存区域。
    void far getfillsetings(struct fillsettingstype far * fillinfo);
    获得现行图模的颜色并将存入结构指针变量fillinfo中。其中fillsettingstype
结构定义如下:
          struct fillsettingstype{
             int pattern; /* 现行填充模式 * /
             int color;    /* 现行填充模式 * /
          };
    有关图形填充图模的颜色的选择, 请看下面例程。
    11:
     #include<graphics.h>
     main(){
        char str[8]={10,20,30,40,50,60,70,80}; /*用户定义图模*/
        int gdriver,gmode,i;
        struct fillsettingstype save; /*定义一个用来存储填充信息的结构变量*/
        gdriver=DETECT;
        initgraph(&gdriver,&gmode,"c://tc");
        setbkcolor(BLUE);
        cleardevice();
        for(i=0;i<13;i++)
       {
        setcolor(i+3);
        setfillstyle(i,2+i);      /* 设置填充类型 *
        bar(100,150,200,50);      /*画矩形并填充*/
        bar3d(300,100,500,200,70,1); /* 画长方体并填充*/
        pieslice(200, 300, 90, 180, 90);/*画扇形并填充*/
        sector(500,300,180,270,200,100);/*画椭圆扇形并填充*/
        delay(1000);                    /*延时1秒*/
        }
       cleardevice();
       setcolor(14);
       setfillpattern(str, RED);
       bar(100,150,200,50);
       bar3d(300,100,500,200,70,0);
       pieslice(200,300,0,360,90);
       sector(500,300,0,360,100,50);
       getch();
       getfillsettings(&save);       /*获得用户定义的填充模式信息*/
       closegraph();
       clrscr();
       printf("The pattern is %d, The color of filling is %d",
             save.pattern, save.color); /*输出目前填充图模和颜色值*/
       getch();
     }
    以上程序运行结束后, 在屏幕上显示出现行填充图模和颜色的常数值。
 
    三、任意封闭图形的填充
    截止目前为止, 我们只能对一些特定形状的封闭图形进行填充, 但还不能对
任意封闭图形进行填充。为此, TURBO C 提供了一个可对任意封闭图形填充的函
, 其调用格式如下:
          void far floodfill(int x, int y, int border);
    其中: x, y为封闭图形内的任意一点。border为边界的颜色, 也就是封闭图
形轮廓的颜色。调用了该函数后, 将用规定的颜色和图模填满整个封闭图形。
    注意:
    1. 如果x或y取在边界上, 则不进行填充。
    2. 如果不是封闭图形则填充会从没有封闭的地方溢出去, 填满其它地方。
    3. 如果x或y在图形外面, 则填充封闭图形外的屏幕区域。
    4. border指定的颜色值必须与图形轮廓的颜色值相同, 但填充色可选任
意颜色。下例是有关floodfill()函数的用法, 该程序填充了bar3d()所画长方体
中其它两个未填充的面。
    12:
     #include<stdlib.h>
     #include<graphics.h>
     main()
     {
          int gdriver, gmode;
          strct fillsettingstype save;
          gdriver=DETECT;
          initgraph(&gdriver, &gmode, "");
          setbkcolor(BLUE);
          cleardevice();
          setcolor(LIGHTRED);
          setlinestyle(0,0,3);
          setfillstyle(1,14);           /*设置填充方式*/
          bar3d(100,200,400,350,200,1); /*画长方体并填充*/
          floodfill(450,300,LIGHTRED); /*填充长方体另外两个面*/
          floodfill(250,150, LIGHTRED);
          rectanle(450,400,500,450);    /*画一矩形*/
          floodfill(470,420, LIGHTRED); /*填充矩形*/
          getch();
          closegraph();
     }
 
    6. 有关图形窗口和图形屏幕操作函数
 
    一、图形窗口操作
    象文本方式下可以设定屏幕窗口一样, 图形方式下也可以在屏幕上某一区域
设定窗口, 只是设定的为图形窗口而已, 其后的有关图形操作都将以这个窗口的
左上角(0,0)作为坐标原点, 而且可为通过设置使窗口之外的区域为不可接触。
这样, 所有的图形操作就被限定在窗口内进行。
    void far setviewport(int xl,int yl,int x2, int y2,int clipflag);
    设定一个以(xl,yl)象元点为左上角, (x2,y2)象元为右下角的图形窗口, 其
x1,y1,x2,y2是相对于整个屏幕的坐标。若clipflag为非0, 则设定的图形以外
部分不可接触, 若clipflag为0, 则图形窗口以外可以接触。
     void far clearviewport(void);
    清除现行图形窗口的内容。
     void far getviewsettings(struct viewporttype far * viewport);
    获得关于现行窗口的信息,并将其存于viewporttype定义的结构变量viewport
, 其中viewporttype的结构说明如下:
         struct viewporttype{
            int left, top, right, bottom;
             int cliplag;
           };
   注明:
     1. 窗口颜色的设置与前面讲过的屏幕颜色设置相同, 但屏幕背景色和窗口
背景色只能是一种颜色, 如果窗口背景色改变, 整个屏幕的背景色也将改变这与
文本窗口不同。
     2. 可以在同一个屏幕上设置多个窗口, 但只能有一个现行窗口工作, 要对
其它窗口操作, 通过将定义那个窗口的setviewport()函数再用一次即可。
     3. 前面讲过图形屏幕操作的函数均适合于对窗口的操作。
 
    二、屏幕操作
    除了清屏函数以外, 关于屏幕操作还有以下函数:
      void far setactivepage(int pagenum);
      void far setvisualpage(int pagenum);
    这两个函数只用于EGA,VGA 以及HERCULES图形适配器。setctivepage() 函数
是为图形输出选择激活页。 所谓激活页是指后续图形的输出被写到函数选定的
pagenum页面, 该页面并不一定可见。setvisualpage()函数才使pagenum 所指定
的页面变成可见页。页面从0开始(Turbo C默认页)。如果先用setactivepage()
函数在不同页面上画出一幅幅图像,再用setvisualpage()函数交替显示, 就可以
实现一些动画的效果。
     void far getimage(int xl,int yl, int x2,int y2, void far *mapbuf);
     void far putimge(int x,int,y,void * mapbuf, int op);
     unsined far imagesize(int xl,int yl,int x2,int y2);
     这三个函数用于将屏幕上的图像复制到内存,然后再将内存中的图像送回到
屏幕上。首先通过函数imagesize()测试要保存左上角为(xl,yl), 右上角为(x2,
y2)的图形屏幕区域内的全部内容需多少个字节, 然后再给mapbuf 分配一个所测
数字节内存空间的指针。通过调用getimage()函数就可将该区域内的图像保存在
内存中, 需要时可用putimage()函数将该图像输出到左上角为点(x, y)的位置上,
其中getimage()函数中的参数op规定如何释放内存中图像。
    关于这个参数的定义参见表8。
 
               8. putimage()函数中的op值
     ━━━━━━━━━━━━━━━━━━━━━━━━━━
            符号常数       数值        
     ──────────────────────────
            COPY_PUT         0       复制
            XOR_PUT          1       与屏幕图像异或的复制
            OR_PUT           2       与屏幕图像或后复制
            AND_PUT          3       与屏幕图像与后复制
            NOT_PUT          4       复制反像的图形
     ━━━━━━━━━━━━━━━━━━━━━━━━━━
 
    对于imagesize()函数, 只能返回字节数小于64K字节的图像区域, 否则将会
出错, 出错时返回-1。
    本节介绍的函数在图像动画处理、菜单设计技巧中非常有用。
 
    13: 下面程序模拟两个小球动态碰撞过程。
     #include<stdio.h>
     #include<graphics.h>
     int main()
     {
          int i, gdriver, gmode, size;
          void *buf;
          gdriver=DETECT;
          initgraph(&gdriver, &gmode, "");
          setbkcolor(BLUE);
          cleardevice();
          setcolor(LIGHTRED);
          setlinestyle(0,0,1);
          setfillstyle(1, 10);
          circle(100, 200, 30);
          floodfill(100, 200, 12);
          size=imagesize(69, 169, 131, 231);
          buf=malloc(size);
          getimage(69, 169, 131, 231,buf);
          putimage(500, 269, buf, COPY_PUT);
          for(i=0; i<185; i++){
               putimage(70+i, 170, buf, COPY_PUT);
               putimage(500-i, 170, buf, COPY_PUT);
          }
          for(i=0;i<185; i++){
               putimage(255-i, 170, buf, COPY_PUT);
               putimage(315+i, 170, buf, COPY_PUT);
          }
          getch();
          closegraph();
        }
 
    7. 图形模式下的文本输出
 
    在图形模式下, 只能用标准输出函数, 如printf(), puts(), putchar() 函
数输出文本到屏幕。除此之外, 其它输出函数(如窗口输出函数)不能使用, 即是
可以输出的标准函数, 也只以前景色为白色, 按80列, 25行的文本方式输出。
    Turbo C2.0也提供了一些专门用于在图形显示模式下的文本输出函数。下面
将分别进行介绍。
    一、文本输出函数
     void far outtext(char far *textstring);
    该函数输出字符串指针textstring所指的文本在现行位置。
     void far outtextxy(int x, int y, char far *textstring);
    该函数输出字符串指针textstring所指的文本在规定的(x, y)位置。 其中x
y为象元坐标。
    说明:
     这两个函数都是输出字符串, 但经常会遇到输出数值或其它类型的数据,
此时就必须使用格式化输出函数sprintf()。
    sprintf()函数的调用格式为:
       int sprintf(char *str, char *format, variable-list);
    它与printf()函数不同之处是将按格式化规定的内容写入str 指向的字符串
, 返回值等于写入的字符个数。
    例如:
       sprintf(s, "your TOEFL score is %d", mark);
    这里s应是字符串指针或数组, mark为整型变量。
 
    二、有关文本字体、字型和输出方式的设置
    有关图形方式下的文本输出函数, 可以通过setcolor()函数设置输出文本的
颜色。另外, 也可以改变文本字体大小以及选择是水平方向输出还是垂直方向输
出。
 
     void far settexjustify(int horiz, int vert);
    该函数用于定位输出字符串。
    对使用outtextxy(int x, int y, char far *str textstring) 函数所输出
的字符串, 其中哪个点对应于定位坐标(x, y)在Turbo C2.0中是有规定的。如果
把一个字符串看成一个长方形的图形, 在水平方向显示时, 字符串长方形按垂直
方向可分为顶部, 中部和底部三个位置, 水平方向可分为左, 中, 右三个位置,
两者结合就有9个位置。
    settextjustify()函数的第一个参数horiz指出水平方向三个位置中的一个,
第二个参数vert指出垂直方向三个位置中的一个, 二者就确定了其中一个位置。
当规定了这个位置后, 用outtextxy()函数输出字符串时, 字符串长方形的这个
规定位置就对准函数中的(x, y)位置。而对用outtext()函数输出字符串时, 这
个规定的位置就位于现行游标的位置。有关参数horiz和vert的取值参见表9。
 
              9. 参数horiz和vert的取值
    ━━━━━━━━━━━━━━━━━━━━━━━━
       符号常数          数值           用于
    ────────────────────────
     LEFT_TEXT             0            水平
     RIGHT_TEXT            2            水平
     BOTTOM_TEXT           0            垂直
     TOP_TEXT              2            垂直
     CENTER_TEXT           1            水平或垂直
    ━━━━━━━━━━━━━━━━━━━━━━━━
 
      void far settextstyle(int font, int direction, int charsize);
    该函数用来设置输出字符的字形(由font确定)、输出方向(由direction确定)
和字符大小(由charsize确定)等特性。Turbo C2.0对函数中各个参数的规定见下
列各表所示:
 
               10. font的取值
     ━━━━━━━━━━━━━━━━━━━━━━━━
        符号常数         数值      含义
     ────────────────────────
      DEFAULT_FONT         0       8*8点阵字(缺省值)
      TRIPLEX_FONT         1       三倍笔划字体
      SMALL_FONT           2       小号笔划字体
      SANSSERIF_FONT       3       无衬线笔划字体
      GOTHIC_FONT          4       黑体笔划字
     ━━━━━━━━━━━━━━━━━━━━━━━━
 
               11. direction的取值
     ━━━━━━━━━━━━━━━━━━━━━━━━
       符号常数          数值        含义
     ────────────────────────
       HORIZ_DIR           0         从左到右
       VERT_DIR            1         从底到顶
     ━━━━━━━━━━━━━━━━━━━━━━━━
 
               12. charsize的取值
     ━━━━━━━━━━━━━━━━━━━━━━━━
       符号常数或数值              含义
     ────────────────────────
          1                        8*8点阵
          2                        16*16点阵
          3                        24*24点阵
          4                        32*32点阵
          5                        40*40点阵
          6                        48*48点阵
          7                        56*56点阵
          8                        64*64点阵
          9                        72*72点阵
         10                        80*80点阵
      USER_CHAR_SIZE=0             用户定义的字符大小
     ━━━━━━━━━━━━━━━━━━━━━━━━
 
 
    有关图形屏幕下文本输出和字体字型设置函数的用法请看下例:
    14:
     #include<graphics.h>
     #include<stdio.h>
     int main()
     {
          int i, gdriver, gmode;
          char s[30];
          gdriver=DETECT;
          initgraph(&gdriver, &gmode, "");
          setbkcolor(BLUE);
          cleardevice();
          setviewport(100, 100, 540, 380, 1); /*定义一个图形窗口*/
          setfillstyle(1, 2);      /*绿色以实填充*/
          setcolor(YELLOW);
          rectangle(0, 0, 439, 279);
          floodfill(50, 50, 14);
          setcolor(12);
          settextstyle(1, 0, 8);   /*三重笔划字体, 水平放大8倍*/
          outtextxy(20, 20, "Good Better");
          setcolor(15);
          settextstyle(3, 0, 5); /*无衬笔划字体, 水平放大5倍*/
          outtextxy(120, 120, "Good Better");
          setcolor(14);
          settextstyle(2, 0, 8);
          i=620;
          sprintf(s, "Your score is %d", i); /*将数字转化为字符串*/
          outtextxy(30, 200, s);      /*指定位置输出字符串*/
          setcolor(1);
          settextstyle(4, 0, 3);
          outtextxy(70, 240, s);
          getch();
          closegraph();
          return 0;
     }
 
    三、用户对文本字符大小的设置
    前面介绍的settextstyle()函数, 可以设定图形方式下输出文本字符这字体
和大小但对于笔划型字体(除8*8点阵字以个的字体), 只能在水平和垂直方向以
相同的放大倍数放大。为此Turbo C2.0又提供了另外一个setusercharsize() 函
, 对笔划字体可以分别设置水平和垂直方向的放大倍数。该函数的调用格式为:
     void far setusercharsize(int mulx, int divx, int muly, int divy);
    该函数用来设置笔划型字和放大系数, 它只有在settextstyle( ) 函数中的
charsize为0(或USER_CHAR_SIZE)时才起作用, 并且字体为函数settextstyle()
规定的字体。调用函数setusercharsize()后, 每个显示在屏幕上的字符都以其
缺省大小乘以mulx/divx为输出字符宽, 乘以muly/divy为输出字符高。该函数的
用法见下例。
 
    15:
     #include<stdio.h>
     #include<graphics.h>
     int main()
     {
          int gdirver, gmode;
          gdriver=DETETC;
          initgraph(&gdriver, &gmode, "");
          setbkcolor(BLUE);
          cleardevice();
          setfillstyle(1, 2); /*设置填充方式*/
          setcolor(WHITE);    /*设置白色作图*/
          rectangle(100, 100, 330, 380);
          floodfill(50, 50, 14);   /*填充方框以外的区域*/
          setcolor(12);       /*作图色为淡红*/
          settextstyle(1, 0, 8);/*三重笔划字体, 放大8倍*/
          outtextxy(120, 120, "Very Good");
          setusercharsize(2, 1, 4, 1);/*水平放大2倍, 垂直放大4倍*/
          setcolor(15);
          settextstyle(3, 0, 5); /*无衬字笔划, 放大5倍*/
          outtextxy(220, 220, "Very Good");
          setusercharsize(4, 1, 1, 1);
          settextstyle(3, 0, 0);
          outtextxy(180, 320, "Good");
          getch();
          closegraph();
          return 0;
     }
  
函数名: abort
 能: 异常终止一个进程
 法: void abort(void);
程序例:
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
 printf("Calling abort()/n");
 abort();
 return 0; /* This is never reached */
}
 
 
 
函数名: abs
 能: 求整数的绝对值
 法: int abs(int i);
程序例:
#include <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <conio.h>
#include <process.h>
#include <dos.h>
 
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 <stdio.h>
#include <io.h>
 
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 <stdio.h>
#include <math.h>
 
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 <dos.h>
#include <alloc.h>
#include <stdio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <string.h>
#include <time.h>
 
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 <stdio.h>
#include <math.h>
 
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 <assert.h>
#include <stdio.h>
#include <stdlib.h>
 
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 <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <stdlib.h>
 
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 <stdlib.h>
#include <stdio.h>
 
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 <stdlib.h>
#include <stdio.h>
 
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 <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   long l;
   char *str = "98765432";
 
   l = atol(lstr);
   printf("string = %s integer = %ld/n", str, l);
   return(0);
}
   
函数名: bar
 能: 画一个二维条形图
 法: void far bar(int left, int top, int right, int bottom);
程序例:
 
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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<USER_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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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<USER_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 <stdio.h>
#include <dos.h>
 
/* 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 <string.h>
#include <stdio.h>
#include <dir.h>
#include <dos.h>
#include <errno.h>
#include <stdlib.h>
 
#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 <bios.h>
#include <conio.h>
 
#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 <bios.h>
#include <stdio.h>
 
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 <bios.h>
#include <stdio.h>
 
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 <stdio.h>
#include <bios.h>
#include <ctype.h>
 
#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 <stdio.h>
#include <bios.h>
 
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 <stdio.h>
#include <conio.h>
#include <bios.h>
 
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 <stdio.h>
#include <bios.h>
#include <time.h>
#include <conio.h>
 
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 <stdio.h>
#include <alloc.h>
 
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 <stdlib.h>
#include <stdio.h>
 
#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;
}
 
函数名: cabs
 能: 计算复数的绝对值
 法: double cabs(struct complex z);
程序例:
 
#include <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <alloc.h>
 
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 <math.h>
#include <stdio.h>
 
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 <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <stdlib.h>
#include <dir.h>
 
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 <sys/stat.h>
#include <stdio.h>
#include <io.h>
 
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 <string.h>
#include <fcntl.h>
#include <io.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
#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 <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
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 <time.h>
#include <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <conio.h>
 
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 <conio.h>
 
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 <stdio.h>
#include <alloc.h>
 
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 <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <math.h>
 
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 <dos.h>
#include <stdio.h>
 
#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 <conio.h>
 
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 <conio.h>
 
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 <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
 
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 <string.h>
#include <stdio.h>
#include <errno.h>
#include <dos.h>
#include <io.h>
 
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 <string.h>
#include <stdio.h>
#include <io.h>
 
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 <conio.h>
 
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 <stdio.h>
#include <time.h>
 
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 <stdio.h>
#include <dos.h>
 
#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 <Ctrl-Break> to quit:/n");
   }
   return 0;
}
 
函数名: delay
 能: 将程序的执行暂停一段时间(毫秒)
 法: void delay(unsigned milliseconds);
程序例:
/* Emits a 440-Hz tone for 500 milliseconds */
#include <dos.h>
 
int main(void)
{
   sound(440);
   delay(500);
   nosound();
 
   return 0;
}
 
 
 
函数名: delline
 能: 在文本窗口中删去一行
 法: void delline(void);
程序例:
 
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <time.h>
#include <stdio.h>
#include <dos.h>
#include <conio.h>
 
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 <stdio.h>
#include <dos.h>
#include <conio.h>
 
#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 <stdlib.h>
#include <stdio.h>
 
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 <stdio.h>
#include <dos.h>
 
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 <time.h>
 #include <stddef.h>
 #include <dos.h>
 #include <stdio.h>
 
 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
 
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 <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>
 
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;
}
函数名: ecvt
 能: 把一个浮点数转换为字符串
 法: char ecvt(double value, int ndigit, int *decpt, int *sign);
程序例:
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <dos.h>
#include <conio.h>
 
/* 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 <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
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 <process.h>
#include <stdio.h>
#include <errno.h>
 
void main(int argc, char *argv[])
{
   int i;
 
   printf("Command line arguments:/n");
   for (i=0; i<argc; 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 <stdlib.h>
#include <conio.h>
#include <stdio.h>
 
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 <stdio.h>
#include <math.h>
 
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;
}
 
 
函数名: fabs
 能: 返回浮点数的绝对值
 法: double fabs(double x);
程序例:
 
#include <stdio.h>
#include <math.h>
 
int main(void)
{
   float number = -1234.0;
 
   printf("number: %f absolute value: %f/n",
   number, fabs(number));
   return 0;
}
 
 
 
 
函数名: farcalloc
 能: 从远堆栈中申请空间
 法: void far *farcalloc(unsigned long units, unsigned ling unitsz);
程序例:
#include <stdio.h>
#include <alloc.h>
#include <string.h>
#include <dos.h>
 
int main(void)
{
   char far *fptr;
   char *str = "Hello";
 
   /* allocate memory for the far pointer */
   fptr = farcalloc(10, sizeof(char));
 
   /* copy "Hello" into allocated memory */
   /*
      Note: movedata is used because you
      might be in a small data model, in
      which case a normal string copy routine
      can not be used since it assumes the
      pointer size is near.
   */
   movedata(FP_SEG(str), FP_OFF(str),
     FP_SEG(fptr), FP_OFF(fptr),
            strlen(str));
 
   /* display string (note the F modifier) */
   printf("Far string is: %Fs/n", fptr);
 
   /* free the memory */
   farfree(fptr);
 
   return 0;
}
 
 
 
 
函数名: farcoreleft
 能: 返回远堆中未作用存储区大小
 法: long farcoreleft(void);
程序例:
 
#include <stdio.h>
#include <alloc.h>
 
int main(void)
{
   printf("The difference between the/
    highest allocated block in the/
           far/n");
   printf("heap and the top of the far heap/
           is: %lu bytes/n", farcoreleft());
 
   return 0;
}
 
 
 
 
函数名: farfree
 能: 从远堆中释放一块
 法: void farfree(void);
程序例:
 
#include <stdio.h>
#include <alloc.h>
#include <string.h>
#include <dos.h>
 
int main(void)
{
   char far *fptr;
   char *str = "Hello";
 
   /* allocate memory for the far pointer */
   fptr = farcalloc(10, sizeof(char));
 
   /* copy "Hello" into allocated memory */
   /*
      Note: movedata is used because you might be in a small data model,
      in which case a normal string copy routine can't be used since it
      assumes the pointer size is near.
   */
   movedata(FP_SEG(str), FP_OFF(str),
            FP_SEG(fptr), FP_OFF(fptr),
            strlen(str));
 
   /* display string (note the F modifier) */
   printf("Far string is: %Fs/n", fptr);
 
   /* free the memory */
   farfree(fptr);
 
   return 0;
}
 
 
 
 
函数名: farmalloc
功  能: 从远堆中分配存储块
 法: void far *farmalloc(unsigned long size);
程序例:
 
#include <stdio.h>
#include <alloc.h>
#include <string.h>
#include <dos.h>
 
int main(void)
{
   char far *fptr;
   char *str = "Hello";
 
   /* allocate memory for the far pointer */
   fptr = farmalloc(10);
 
   /* copy "Hello" into allocated memory */
   /*
      Note: movedata is used because we might
      be in a small data model, in which case
      a normal string copy routine can not be
      used since it assumes the pointer size
      is near.
   */
   movedata(FP_SEG(str), FP_OFF(str),
     FP_SEG(fptr), FP_OFF(fptr),
     strlen(str));
 
   /* display string (note the F modifier) */
   printf("Far string is: %Fs/n", fptr);
 
   /* free the memory */
   farfree(fptr);
 
   return 0;
}
 
 
 
 
函数名: farrealloc
 能: 调整远堆中的分配块
 法: void far *farrealloc(void far *block, unsigned long newsize);
程序例:
 
#include <stdio.h>
#include <alloc.h>
 
int main(void)
{
   char far *fptr;
 
   fptr = farmalloc(10);
   printf("First address: %Fp/n", fptr);
   fptr = farrealloc(fptr,20);
   printf("New address : %Fp/n", fptr);
   farfree(fptr);
   return 0;
}
 
 
 
函数名: fclose
 能: 关闭一个流
 法: int fclose(FILE *stream);
程序例:
 
#include <string.h>
#include <stdio.h>
 
int main(void)
{
   FILE *fp;
   char buf[11] = "0123456789";
 
   /* create a file containing 10 bytes */
   fp = fopen("DUMMY.FIL", "w");
   fwrite(&buf, strlen(buf), 1, fp);
 
   /* close the file */
   fclose(fp);
   return 0;
}
 
 
 
 
函数名: fcloseall
 能: 关闭打开流
 法: int fcloseall(void);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   int streams_closed;
 
   /* open two streams */
   fopen("DUMMY.ONE", "w");
   fopen("DUMMY.TWO", "w");
 
   /* close the open streams */
   streams_closed = fcloseall();
 
   if (streams_closed == EOF)
      /* issue an error message */
      perror("Error");
   else
      /* print result of fcloseall() function */
      printf("%d streams were closed./n", streams_closed);
 
   return 0;
}
  
 
 
函数名: fcvt
 能: 把一个浮点数转换为字符串
 法: char *fcvt(double value, int ndigit, int *decpt, int *sign);
程序例:
 
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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;
}
 
 
 
 
函数名: fdopen
 能: 把流与一个文件句柄相接
 法: FILE *fdopen(int handle, char *type);
程序例:
 
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
int main(void)
{
   int handle;
   FILE *stream;
 
   /* open a file */
   handle = open("DUMMY.FIL", O_CREAT,
    S_IREAD | S_IWRITE);
 
   /* now turn the handle into a stream */
   stream = fdopen(handle, "w");
 
   if (stream == NULL)
      printf("fdopen failed/n");
   else
   {
      fprintf(stream, "Hello world/n");
      fclose(stream);
   }
   return 0;
}
 
 
 
函数名: feof
 能: 检测流上的文件结束符
 法: int feof(FILE *stream);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
 
   /* open a file for reading */
   stream = fopen("DUMMY.FIL", "r");
 
   /* read a character from the file */
   fgetc(stream);
 
   /* check for EOF */
   if (feof(stream))
      printf("We have reached end-of-file/n");
 
   /* close the file */
   fclose(stream);
   return 0;
}
 
 
 
函数名: ferror
 能: 检测流上的错误
 法: int ferror(FILE *stream);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
 
   /* open a file for writing */
   stream = fopen("DUMMY.FIL", "w");
 
   /* force an error condition by attempting to read */
   (void) getc(stream);
 
   if (ferror(stream)) /* test for an error on the stream */
   {
      /* display an error message */
      printf("Error reading from DUMMY.FIL/n");
 
      /* reset the error and EOF indicators */
      clearerr(stream);
   }
 
   fclose(stream);
   return 0;
}
 
 
 
 
函数名: fflush
 能: 清除一个流
 法: int fflush(FILE *stream);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
 
void flush(FILE *stream);
 
int main(void)
{
   FILE *stream;
   char msg[] = "This is a test";
 
   /* create a file */
   stream = fopen("DUMMY.FIL", "w");
 
   /* write some data to the file */
   fwrite(msg, strlen(msg), 1, stream);
 
   clrscr();
   printf("Press any key to flush/
   DUMMY.FIL:");
   getch();
 
   /* flush the data to DUMMY.FIL without/
      closing it */
   flush(stream);
 
   printf("/nFile was flushed, Press any key/
   to quit:");
   getch();
   return 0;
}
 
void flush(FILE *stream)
{
     int duphandle;
 
     /* flush the stream'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);
}
 
 
 
 
函数名: fgetc
 能: 从流中读取字符
 法: int fgetc(FILE *stream);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <conio.h>
 
int main(void)
{
   FILE *stream;
   char string[] = "This is a test";
   char ch;
 
   /* open a file for update */
   stream = fopen("DUMMY.FIL", "w+");
 
   /* write a string into the file */
   fwrite(string, strlen(string), 1, stream);
 
   /* seek to the beginning of the file */
   fseek(stream, 0, SEEK_SET);
 
   do
   {
      /* read a char from the file */
      ch = fgetc(stream);
 
      /* display the character */
      putch(ch);
   } while (ch != EOF);
 
   fclose(stream);
   return 0;
}
 
 
 
 
函数名: fgetchar
 能: 从流中读取字符
 法: int fgetchar(void);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   char ch;
 
   /* prompt the user for input */
   printf("Enter a character followed by /
   <Enter>: ");
 
   /* read the character from stdin */
   ch = fgetchar();
 
   /* display what was read */
   printf("The character read is: '%c'/n",
          ch);
   return 0;
}
 
 
 
 
函数名: fgetpos
 能: 取得当前文件的句柄
 法: int fgetpos(FILE *stream);
程序例:
 
#include <string.h>
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
   char string[] = "This is a test";
   fpos_t filepos;
 
   /* open a file for update */
   stream = fopen("DUMMY.FIL", "w+");
 
  /* write a string into the file */
   fwrite(string, strlen(string), 1, stream);
 
   /* report the file pointer position */
   fgetpos(stream, &filepos);
   printf("The file pointer is at byte/
          %ld/n", filepos);
 
   fclose(stream);
   return 0;
}
 
 
 
 
函数名: fgets
 能: 从流中读取一字符串
 法: char *fgets(char *string, int n, FILE *stream);
程序例:
 
#include <string.h>
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
   char string[] = "This is a test";
   char msg[20];
 
   /* open a file for update */
   stream = fopen("DUMMY.FIL", "w+");
 
   /* write a string into the file */
   fwrite(string, strlen(string), 1, stream);
 
   /* seek to the start of the file */
   fseek(stream, 0, SEEK_SET);
 
   /* read a string from the file */
   fgets(msg, strlen(string)+1, stream);
 
   /* display the string */
   printf("%s", msg);
 
   fclose(stream);
   return 0;
}
 
 
 
 
函数名: filelength
 能: 取文件长度字节数
 法: long filelength(int handle);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
int main(void)
{
   int handle;
   char buf[11] = "0123456789";
 
   /* create a file containing 10 bytes */
   handle = open("DUMMY.FIL", O_CREAT);
   write(handle, buf, strlen(buf));
 
   /* display the size of the file */
   printf("file length in bytes: %ld/n",
   filelength(handle));
 
   /* close the file */
   close(handle);
   return 0;
}
 
 
 
函数名: fillellipse
 能: 画出并填充一椭圆
 法: void far fillellipse(int x, int y, int xradius, int yradius);
程序例:
 
#include <graphics.h>
#include <conio.h>
 
int main(void)
{
   int gdriver = DETECT, gmode;
   int xcenter, ycenter, i;
 
   initgraph(&gdriver,&gmode,"");
   xcenter = getmaxx() / 2;
   ycenter = getmaxy() / 2;
 
   for (i=0; i<13; i++)
   {
      setfillstyle(i,WHITE);
      fillellipse(xcenter,ycenter,100,50);
      getch();
   }
 
   closegraph();
   return 0;
}
 
 
 
 
函数名: fillpoly
 能: 画并填充一个多边形
 法: void far fillpoly(int numpoints, int far *polypoints);
程序例:
 
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
int main(void)
{
   /* request auto detection */
   int gdriver = DETECT, gmode, errorcode;
   int i, maxx, maxy;
 
   /* our polygon array */
   int poly[8];
 
   /* 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 */
   }
 
   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;
 
   /*
      4th vertex. fillpoly automatically
      closes the polygon.
   */
   poly[6] = maxx / 2;
   poly[7] = maxy / 2;
 
   /* loop through the fill patterns */
   for (i=EMPTY_FILL; i<USER_FILL; i++)
   {
      /* set fill pattern */
      setfillstyle(i, getmaxcolor());
 
      /* draw a filled polygon */
      fillpoly(4, poly);
 
      getch();
   }
 
   /* clean up */
   closegraph();
   return 0;
}
 
 
 
 
函数名: findfirst, findnext
 能: 搜索磁盘目录; 取得下一个匹配的findfirst模式的文件
 法: int findfirst(char *pathname, struct ffblk *ffblk, int attrib);
 int findnext(struct ffblk *ffblk);
程序例:
 
/* findnext example */
 
#include <stdio.h>
#include <dir.h>
 
int main(void)
{
   struct ffblk ffblk;
   int done;
   printf("Directory listing of *.*/n");
   done = findfirst("*.*",&ffblk,0);
   while (!done)
   {
      printf(" %s/n", ffblk.ff_name);
      done = findnext(&ffblk);
   }
 
   return 0;
}
 
 
 
 
函数名: floodfill
 能: 填充一个有界区域
 法: void far floodfill(int x, int y, int border);
程序例:
 
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
int main(void)
{
   /* request auto detection */
   int gdriver = DETECT, gmode, errorcode;
   int maxx, maxy;
 
   /* 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 */
   }
 
   maxx = getmaxx();
   maxy = getmaxy();
 
   /* select drawing color */
   setcolor(getmaxcolor());
 
   /* select fill color */
   setfillstyle(SOLID_FILL, getmaxcolor());
 
   /* draw a border around the screen */
   rectangle(0, 0, maxx, maxy);
 
   /* draw some circles */
   circle(maxx / 3, maxy /2, 50);
   circle(maxx / 2, 20, 100);
   circle(maxx-20, maxy-50, 75);
   circle(20, maxy-20, 25);
 
   /* wait for a key */
   getch();
 
   /* fill in bounded region */
   floodfill(2, 2, getmaxcolor());
 
   /* clean up */
   getch();
   closegraph();
   return 0;
}
 
 
 
 
函数名: floor
 能: 向下舍入
 法: double floor(double x);
程序例:
 
#include <stdio.h>
#include <math.h>
 
int main(void)
{
   double number = 123.54;
   double down, up;
 
   down = floor(number);
   up = ceil(number);
 
   printf("original number     %10.2lf/n",
          number);
   printf("number rounded down %10.2lf/n",
          down);
   printf("number rounded up   %10.2lf/n",
          up);
 
   return 0;
}
 
 
 
 
函数名: flushall
 能: 清除所有缓冲区
 法: int flushall(void);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
 
   /* create a file */
   stream = fopen("DUMMY.FIL", "w");
 
   /* flush all open streams */
   printf("%d streams were flushed./n",
   flushall());
 
   /* close the file */
   fclose(stream);
   return 0;
}
 
 
 
 
函数名: fmod
 能: 计算x对y的模, 即x/y的余数
 法: double fmod(double x, double y);
程序例:
 
#include <stdio.h>
#include <math.h>
 
int main(void)
{
   double x = 5.0, y = 2.0;
   double result;
 
   result = fmod(x,y);
   printf("The remainder of (%lf / %lf) is /
          %lf/n", x, y, result);
   return 0;
}
 
 
 
 
函数名: fnmerge
 能: 建立新文件名
 法: void fnerge(char *path, char *drive, char *dir);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <dir.h>
 
 
int main(void)
{
    char s[MAXPATH];
    char drive[MAXDRIVE];
    char dir[MAXDIR];
    char file[MAXFILE];
    char ext[MAXEXT];
 
    getcwd(s,MAXPATH);              /* get the current working directory */
    strcat(s,"//");                  /* append on a trailing / character */
    fnsplit(s,drive,dir,file,ext); /* split the string to separate elems */
    strcpy(file,"DATA");
    strcpy(ext,".TXT");
    fnmerge(s,drive,dir,file,ext);   /* merge everything into one string */
    puts(s);                                 /* display resulting string */
 
    return 0;
}
 
 
 
 
函数名: fopen
 能: 打开一个流
 法: FILE *fopen(char *filename, char *type);
程序例:
 
#include <stdlib.h>
#include <stdio.h>
#include <dir.h>
 
int main(void)
{
    char *s;
    char drive[MAXDRIVE];
    char dir[MAXDIR];
    char file[MAXFILE];
    char ext[MAXEXT];
    int flags;
 
    s=getenv("COMSPEC"); /* get the comspec environment parameter */
    flags=fnsplit(s,drive,dir,file,ext);
 
    printf("Command processor info:/n");
    if(flags & DRIVE)
       printf("/tdrive: %s/n",drive);
    if(flags & DIRECTORY)
       printf("/tdirectory: %s/n",dir);
    if(flags & FILENAME)
       printf("/tfile: %s/n",file);
    if(flags & EXTENSION)
       printf("/textension: %s/n",ext);
 
    return 0;
}
 
 
函数名: fprintf
 能: 传送格式化输出到一个流中
 法: int fprintf(FILE *stream, char *format[, argument,...]);
程序例:
 
/* Program to create backup of the
   AUTOEXEC.BAT file */
 
#include <stdio.h>
 
int main(void)
{
   FILE *in, *out;
 
   if ((in = fopen("//AUTOEXEC.BAT", "rt"))
       == NULL)
   {
      fprintf(stderr, "Cannot open input /
       file./n");
      return 1;
   }
 
   if ((out = fopen("//AUTOEXEC.BAK", "wt"))
       == NULL)
   {
      fprintf(stderr, "Cannot open output /
       file./n");
      return 1;
   }
 
   while (!feof(in))
      fputc(fgetc(in), out);
 
   fclose(in);
   fclose(out);
   return 0;
}
 
 
 
 
函数名: FP_OFF
 能: 获取远地址偏移量
 法: unsigned FP_OFF(void far *farptr);
程序例:
 
/* FP_OFF */
 
#include <dos.h>
#include <stdio.h>
 
int main(void)
{
   char *str = "fpoff.c";
 
   printf("The offset of this file in memory/
          is: %Fp/n", FP_OFF(str));
 
   return 0;
}
 
 
 
函数名: FP_SEG
 能: 获取远地址段值
 法: unsigned FP_SEG(void far *farptr);
程序例:
 
/* FP_SEG */
 
#include <dos.h>
#include <stdio.h>
 
int main(void)
{
   char *filename = "fpseg.c";
 
   printf("The offset of this file in memory/
   is: %Fp/n", FP_SEG(filename));
 
   return(0);
}
 
 
 
 
函数名: fputc
 能: 送一个字符到一个流中
 法: int fputc(int ch, FILE *stream);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   char msg[] = "Hello world";
   int i = 0;
 
   while (msg[i])
  {
      fputc(msg[i], stdout);
      i++;
   }
   return 0;
}
 
 
 
 
函数名: fputchar
 能: 送一个字符到标准输出流(stdout)中
 法: int fputchar(char ch);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   char msg[] = "This is a test";
   int i = 0;
 
   while (msg[i])
   {
      fputchar(msg[i]);
      i++;
   }
   return 0;
}
 
 
 
 
函数名: fputs
 能: 送一个字符到一个流中
 法: int fputs(char *string, FILE *stream);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   /* write a string to standard output */
   fputs("Hello world/n", stdout);
 
   return 0;
}
 
 
 
 
函数名: fread
 能: 从一个流中读数据
 法: int fread(void *ptr, int size, int nitems, FILE *stream);
程序例:
 
#include <string.h>
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
   char msg[] = "this is a test";
   char buf[20];
 
   if ((stream = fopen("DUMMY.FIL", "w+"))
       == NULL)
   {
      fprintf(stderr,
              "Cannot open output file./n");
      return 1;
   }
 
   /* write some data to the file */
   fwrite(msg, strlen(msg)+1, 1, stream);
 
   /* seek to the beginning of the file */
   fseek(stream, SEEK_SET, 0);
 
   /* read the data and display it */
   fread(buf, strlen(msg)+1, 1, stream);
   printf("%s/n", buf);
 
   fclose(stream);
   return 0;
}
 
 
 
函数名: free
 能: 释放已分配的块
 法: void free(void *ptr);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <alloc.h>
 
int main(void)
{
   char *str;
 
   /* allocate memory for string */
   str = malloc(10);
 
   /* copy "Hello" to string */
   strcpy(str, "Hello");
 
   /* display string */
   printf("String is %s/n", str);
 
   /* free memory */
   free(str);
 
   return 0;
}
 
 
函数名: freemem
 能: 释放先前分配的DOS内存块
 法: int freemem(unsigned seg);
程序例:
 
#include <dos.h>
#include <alloc.h>
#include <stdio.h>
 
int main(void)
{
   unsigned int size, segp;
   int stat;
 
   size = 64; /* (64 x 16) = 1024 bytes */
   stat = allocmem(size, &segp);
   if (stat < 0)
      printf("Allocated memory at segment:/
      %x/n", segp);
   else
      printf("Failed: maximum number of/
      paragraphs available is %u/n",
      stat);
   freemem(segp);
 
   return 0;
}
 
 
 
函数名: freopen
 能: 替换一个流
 法: FILE *freopen(char *filename, char *type, FILE *stream);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   /* redirect standard output to a file */
   if (freopen("OUTPUT.FIL", "w", stdout)
       == NULL)
      fprintf(stderr, "error redirecting/
              stdout/n");
 
   /* this output will go to a file */
   printf("This will go into a file.");
 
   /* close the standard output stream */
   fclose(stdout);
 
   return 0;
}
 
 
 
 
函数名: frexp
 能: 把一个双精度数分解为尾数的指数
 法: double frexp(double value, int *eptr);
程序例:
 
#include <math.h>
#include <stdio.h>
 
int main(void)
{
   double mantissa, number;
   int exponent;
 
   number = 8.0;
   mantissa = frexp(number, &exponent);
 
   printf("The number %lf is ", number);
   printf("%lf times two to the ", mantissa);
   printf("power of %d/n", exponent);
 
   return 0;
}
 
 
 
函数名: fscanf
 能: 从一个流中执行格式化输入
 法: int fscanf(FILE *stream, char *format[,argument...]);
程序例:
 
#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   int i;
 
   printf("Input an integer: ");
 
   /* read an integer from the
      standard input stream */
   if (fscanf(stdin, "%d", &i))
      printf("The integer read was: %i/n",
             i);
   else
   {
     fprintf(stderr, "Error reading an /
              integer from stdin./n");
      exit(1);
   }
   return 0;
}
 
 
 
 
函数名: fseek
 能: 重定位流上的文件指针
 法: int fseek(FILE *stream, long offset, int fromwhere);
程序例:
 
#include <stdio.h>
 
long filesize(FILE *stream);
 
int main(void)
{
   FILE *stream;
 
   stream = fopen("MYFILE.TXT", "w+");
   fprintf(stream, "This is a test");
   printf("Filesize of MYFILE.TXT is %ld bytes/n", filesize(stream));
   fclose(stream);
   return 0;
}
 
long filesize(FILE *stream)
{
   long curpos, length;
 
   curpos = ftell(stream);
   fseek(stream, 0L, SEEK_END);
   length = ftell(stream);
   fseek(stream, curpos, SEEK_SET);
   return length;
}
 
 
 
 
 
 
函数名: fsetpos
 能: 定位流上的文件指针
 法: int fsetpos(FILE *stream, const fpos_t *pos);
程序例:
 
#include <stdlib.h>
#include <stdio.h>
 
void showpos(FILE *stream);
 
int main(void)
{
   FILE *stream;
   fpos_t filepos;
 
   /* open a file for update */
  stream = fopen("DUMMY.FIL", "w+");
 
   /* save the file pointer position */
   fgetpos(stream, &filepos);
 
   /* write some data to the file */
   fprintf(stream, "This is a test");
 
   /* show the current file position */
   showpos(stream);
 
   /* set a new file position, display it */
   if (fsetpos(stream, &filepos) == 0)
     showpos(stream);
   else
   {
      fprintf(stderr, "Error setting file /
       pointer./n");
      exit(1);
   }
 
   /* close the file */
   fclose(stream);
  return 0;
}
 
void showpos(FILE *stream)
{
   fpos_t pos;
 
   /* display the current file pointer
      position of a stream */
   fgetpos(stream, &pos);
   printf("File position: %ld/n", pos);
}
 
 
函数名: fstat
 能: 获取打开文件信息
 法: int fstat(char *handle, struct stat *buff);
程序例:
 
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
 
int main(void)
{
   struct stat statbuf;
   FILE *stream;
 
   /* open a file for update */
   if ((stream = fopen("DUMMY.FIL", "w+"))
       == NULL)
   {
      fprintf(stderr, "Cannot open output /
              file./n");
      return(1);
   }
   fprintf(stream, "This is a test");
   fflush(stream);
 
   /* get information about the file */
   fstat(fileno(stream), &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;
}
 
 
 
 
函数名: ftell
 能: 返回当前文件指针
 法: long ftell(FILE *stream);
程序例:
 
#include <stdio.h>
 
int main(void)
{
   FILE *stream;
 
   stream = fopen("MYFILE.TXT", "w+");
   fprintf(stream, "This is a test");
   printf("The file pointer is at byte /
          %ld/n", ftell(stream));
   fclose(stream);
   return 0;
}
 
 
 
 
函数名: fwrite
 能: 写内容到流中
 法: int fwrite(void *ptr, int size, int nitems, FILE *stream);
程序例:
 
#include <stdio.h>
 
struct mystruct
{
 int i;
 char ch;
};
 
int main(void)
{
   FILE *stream;
   struct mystruct s;
 
   if ((stream = fopen("TEST.$$$", "wb")) == NULL) /* open file TEST.$$$ */
   {
      fprintf(stderr, "Cannot open output file./n");
      return 1;
   }
   s.i = 0;
   s.ch = 'A';
   fwrite(&s, sizeof(s), 1, stream); /* write struct s to file */
   fclose(stream); /* close file */
   return 0;
}
 
函数名: gcvt
 能: 把浮点数转换成字符串
 法: char *gcvt(double value, int ndigit, char *buf);
程序例:
 
#include <stdlib.h>
#include <stdio.h>
 
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 <conio.h>
#include <dos.h>
 
/* 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
 
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 <stdio.h>
#include <dos.h>
 
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 <stdio.h>
#include <conio.h>
 
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 <stdio.h>
 
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 <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
 
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 <dir.h>
#include <stdio.h>
#include <string.h>
 
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 <stdio.h>
#include <dir.h>
 
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 <dos.h>
#include <stdio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <dir.h>
 
int main(void)
{
   int disk;
 
   disk = getdisk() + 'A';
   printf("The current drive is: %c/n",
    disk);
   return 0;
}
 
 
 
 
函数名: getdrivername
 能: 返回指向包含当前图形驱动程序名字的字符串指针
 法: char *getdrivename(void);
程序例:
 
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <dos.h>
#include <stdio.h>
 
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 <stdlib.h>
#include <stdio.h>
 
 
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 <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/ 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 <stdio.h>
#include <io.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <io.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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<pal.size; i++, y+=ht)
      {
 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 <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
 
#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<PIXEL_COUNT; i++)
      {
         x = random(maxx);
         y = random(maxy);
         color = random(maxcolor);
         putpixel(x, y, color);
      }
 
      delay(DELAY_TIME);
      srand(seed);
      for (i=0; i<PIXEL_COUNT; i++)
      {
         x = random(maxx);
         y = random(maxy);
         color = random(maxcolor);
         if (color == getpixel? ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;h;(;);;; ;e;t;p;s;p;(;););;; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;e;s;e;t; ;t;o; ;s;e;g;m;e;n;t; ;o;f; ;t;h;e; ;P;S;P; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;i;n;e; ;i;s; ;l;o;c;a;t;e;d; ;a;t; ;o;f;f;s;e;t; ;0;x;8;1; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;t; ;o;f; ;P;S;P; ; ; ; ; ; ; ; ;
 
 
函数名: gets
 能: 从流中取一字符串
 法: char *gets(char *string);
程序例:
 
#include <stdio.h>
 
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 <conio.h>
 
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 <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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   <stdio.h>
#include   <dos.h>
 
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 <stdio.h>
#include <dos.h>
 
void interrupt get_out(); /* interrupt prototype */
 
void interrupt (*oldfunc)(); /* interrupt function pointer */
int looping = 1;
 
int main(void)
{
 puts("Press <Shift><Prt Sc> 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 <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <stdlib.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <dos.h>
 
/* 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 <conio.h>
 
int main(void)
{
   clrscr();
   gotoxy(35, 12);
   cprintf("Hello world");
   getch();
   return 0;
}
 
 
 
函数名: gotoxy
 能: 在文本窗口中设置光标
 法: void gotoxy(int x, int y);
程序例:
 
#include <conio.h>
 
int main(void)
{
   clrscr();
   gotoxy(35, 12);
   cprintf("Hello world");
   getch();
   return 0;
}
 
 
 
函数名: graphdefaults
 能: 将所有图形设置复位为它们的缺省值
 法: void far graphdefaults(void);
程序例:
 
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <alloc.h>
 
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);
}
 
函数名: 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 <stdio.h>
#include <conio.h>
#include <dos.h>
#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 <stdio.h>
#include <conio.h>
#include <dos.h>
 
#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 <conio.h>
 
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 <stdio.h>
#include <math.h>
 
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;
}
 
 
函数名: imagesize
 能: 返回保存位图像所需的字节数
 法: unsigned far imagesize(int left, int top, int right, int bottom);
程序例:
 
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <dos.h>
 
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 <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <stdio.h>
#include <conio.h>
#include <dos.h>
 
#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, &regs, &regs);
}
 
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 <dos.h>
#include <process.h>
#include <stdio.h>
 
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 <stdio.h>
#include <dos.h>
 
/* 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(&regs, &regs);
 
   /* 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 <stdio.h>
#include <dos.h>
 
/* 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(&regs, &regs, &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 <stdio.h>
#include <string.h>
#include <dir.h>
#include <dos.h>
 
#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, &reg);
   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 <stdio.h>
#include <dir.h>
#include <io.h>
 
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 <stdio.h>
#include <io.h>
 
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 <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   int number = 12345;
   char string[25];
 
   itoa(number, string, 10);
   printf("integer = %d string = %s/n", number, string);
   return 0;
}
 
函数名: kbhit
 能: 检查当前按下的键
 法: int kbhit(void);
程序例:
 
#include <conio.h>
 
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 <dos.h>
/* 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;
}
 
函数名: labs
 能: 取长整型绝对值
 法: long labs(long n);
程序例:
 
#include <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <math.h>
 
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 <stdlib.h>
#include <stdio.h>
 
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 <stdio.h>
#include <stdlib.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <time.h>
#include <stdio.h>
#include <dos.h>
 
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 <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
 
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 <math.h>
#include <stdio.h>
 
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 <math.h>
#include <stdio.h>
 
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 <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
 
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 <conio.h>
 
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 <stdlib.h>
#include <stdio.h>
 
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 <stdio.h>
#include <stdlib.h>
 
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 <sys/stat.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
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;
}
                      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 <stdio.h>
     #include <stdlib.h>
     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<math.h>
 
int matherr(struct exception *a)
{
   return 1;
}
 
 
 
 
函数名: memccpy
 能: 从源source中拷贝n个字节到目标destin中
 法: void *memccpy(void *destin, void *source, unsigned char ch,
       unsigned n);
程序例:
 
#include <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
#include <alloc.h>
#include <process.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
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 <stdio.h>
#include <string.h>
 
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 <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
#include <mem.h>
 
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 <stdio.h>
#include <conio.h>
#include <process.h>
#include <dir.h>
 
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 <dir.h>
#include <stdio.h>
 
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 <dos.h>
#include <graphics.h>
 
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 <math.h>
#include <stdio.h>
 
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 <mem.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <conio.h>
#include <string.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <mem.h>
#include <alloc.h>
#include <stdio.h>
#include <string.h>
 
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 <conio.h>
 
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();
}
 
函数名: open
 能: 打开一个文件用于读或写
 法: int open(char *pathname, int access[, int permiss]);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
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 <stdio.h>
#include <dos.h>
 
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 <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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;
}
 
函数名: parsfnm
功 能: 分析文件名
用 法: char *parsfnm (char *cmdline, struct fcb *fcbptr, int option);
程序例:
 
#include <process.h>
#include <string.h>
#include <stdio.h>
#include <dos.h>
 
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 <stdio.h>
#include <conio.h>
#include <dos.h>
 
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 <stdio.h>
#include <conio.h>
#include <dos.h>
 
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 <stdio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <dos.h>
#include <conio.h>
 
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 <dos.h>
#include <conio.h>
 
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 <stdio.h>
#include <math.h>
 
/* 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 <math.h>
#include <stdio.h>
 
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 <math.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
 
#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 <stdio.h>
 
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 <stdio.h>
#include <conio.h>
 
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 <stdio.h>
 
/* 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 <stdio.h>
#include <stdlib.h>
#include <alloc.h>
#include <string.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <dos.h>
 
#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<PIXEL_COUNT; i++)
      {
 x = random(maxx);
         y = random(maxy);
         color = random(maxcolor);
         putpixel(x, y, color);
      }
 
      delay(DELAY_TIME);
      srand(seed);
      for (i=0; i<PIXEL_COUNT; 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 <stdio.h>
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 <conio.h>
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 <stdio.h>
#include <stdlib.h>
 
#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;
}
 
函数名: qsort
功 能: 使用快速排序例程进行排序
用 法: void qsort(void *base, int nelem, int width, int (*fcmp)());
程序例:
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
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 <signal.h>
 
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 <stdlib.h>
#include <stdio.h>
 
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 <process.h>
#include <string.h>
#include <stdio.h>
#include <dos.h>
 
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 <process.h>
#include <string.h>
#include <stdio.h>
#include <dos.h>
 
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 <stdlib.h>
#include <stdio.h>
#include <time.h>
 
/* 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 <stdlib.h>
#include <stdio.h>
#include <time.h>
 
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 <stdio.h>
#include <io.h>
#include <alloc.h>
#include <fcntl.h>
#include <process.h>
#include <sys/stat.h>
 
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 <stdio.h>
#include <alloc.h>
#include <string.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
 
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 <stdio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <dir.h>
 
 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 <stdio.h>
#include <conio.h>
#include <process.h>
#include <dir.h>
 
#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;
}
 
函数名: sbrk
功 能: 改变数据段空间位置
用 法: char *sbrk(int incr);
程序例:
 
#include <stdio.h>
#include <alloc.h>
 
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 <stdio.h>
#include <conio.h>
 
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<entries;++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); -------------------
 北极星书库||http://www.ebook007.com
 
   for (loop=0;loop<entries;++loop)
      printf("%4d | %-20s | %5d | %15.2lf/n",
         loop + 1,
 entry[loop].name,
 entry[loop].age,
         entry[loop].salary);
   return 0;
}
 
 
 
函数名: searchpath
功 能: 搜索DOS路径
用 法: char *searchpath(char *filename);
程序例:
 
#include <stdio.h>
#include <dir.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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<USER_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 <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <dos.h>
#include <alloc.h>
#include <stdio.h>
#include <stdlib.h>
 
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 <stdio.h>
 
/* 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 <dos.h>
#include <conio.h>
#include <stdio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <process.h>
#include <dos.h>
 
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 <stdio.h>
#include <dir.h>
 
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 <process.h>
#include <string.h>
#include <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <stdio.h>
#include <process.h>
#include <fcntl.h>
#include <io.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <process.h>
#include <setjmp.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <stdio.h>
#include <alloc.h>
#include <mem.h>
 
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 <stdio.h>
#include <fcntl.h>
#include <io.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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<pal.size; 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<pal.size; 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
/* 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 <stdio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
 
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 <stdio.h>
#include <dos.h>
#include <conio.h>
 
#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 <stdio.h>
#include <conio.h>
#include <dos.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
#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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <signal.h>
 
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 <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <math.h>
 
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 <dos.h>
#include <stdio.h>
 
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 <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
 
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 <dos.h>
 
int main(void)
{
   sound(7);
   delay(10000);
   nosound();
   return 0;
}
 
 
 
 
函数名: spawnl
功 能: 创建并运行子程序
用 法: int spawnl(int mode, char *pathname, char *arg0,
     arg1, ... argn, NULL);
程序例:
 
#include <process.h>
#include <stdio.h>
#include <conio.h>
 
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 <process.h>
#include <stdio.h>
#include <conio.h>
 
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 <stdio.h>
#include <math.h>
 
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 <math.h>
 #include <stdio.h>
 
 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 <stdlib.h>
#include <stdio.h>
#include <time.h>
 
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 <stdio.h>
#include <conio.h>
 
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<entries;++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);
   for (loop=0;loop<entries;++loop)
      printf("%4d | %-20s | %5d | %15.2lf/n",
         loop + 1,
 entry[loop].name,
 entry[loop].age,
 entry[loop].salary);
   return 0;
}
 
 
 
函数名: stat
功 能: 读取打开文件信息
用 法: int stat(char *pathname, struct stat *buff);
程序例:
 
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
 
#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 <stdio.h>
#include <float.h>
 
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 <stdio.h>
#include <time.h>
#include <dos.h>
 
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 <stdio.h>
#include <string.h>
 
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 <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
 
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 <stdio.h>
#include <string.h>
#include <alloc.h>
 
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 <stdio.h>
#include <string.h>
#include <alloc.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <errno.h>
 
int main(void)
{
   char *buffer;
   buffer = strerror(errno);
   printf("Error: %s/n", buffer);
   return 0;
}
 
 
 
 
函数名: strcmpi
功 能: 将一个串与另一个比较, 不管大小写
用 法: int strcmpi(char *str1, char *str2);
程序例:
 
#include <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
 
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 <stdio.h>
#include <string.h>
 
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 <string.h>
#include <stdio.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
 
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 <stdio.h>
#include <string.h>
#include <alloc.h>
 
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 <stdio.h>
#include <string.h>
 
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 <stdio.h>
#include <stdlib.h>
 
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 <string.h>
#include <stdio.h>
 
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 <stdlib.h>
#include <stdio.h>
 
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 <stdio.h>
#include <string.h>
 
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 <stdlib.h>
#include <stdio.h>
#include <string.h>
 
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 <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   system("dir");
   return 0;
}
 
函数名: tan
功 能: 正切函数
用 法: double tan(double x);
程序例:
 
#include <stdio.h>
#include <math.h>
 
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 <stdio.h>
#include <math.h>
 
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 <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
 
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 <conio.h>
 
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 <conio.h>
 
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 <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <conio.h>
 
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 <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
 
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 <time.h>
#include <stdio.h>
#include <dos.h>
 
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 <stdio.h>
#include <process.h>
 
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 <stdio.h>
 
int main(void)
{
   char name[13];
 
   tmpnam(name);
   printf("Temporary name: %s/n", name);
   return 0;
}
 
 
 
 
函数名: tolower
功 能: 把字符转换成小写字母
用 法: int tolower(int c);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <ctype.h>
 
int main(void)
{
   int length, i;
   char *string = "THIS IS A STRING";
 
   length = strlen(string);
   for (i=0; i<length; i++)
   {
       string[i] = tolower(string[i]);
   }
   printf("%s/n",string);
 
   return 0;
}
 
 
 
函数名: toupper
功 能: 把字符转换成大写字母
用 法: int toupper(int c);
程序例:
 
#include <string.h>
#include <stdio.h>
#include <ctype.h>
 
int main(void)
{
   int length, i;
   char *string = "this is a string";
 
   length = strlen(string);
   for (i=0; i<length; i++)
   {
      string[i] = toupper(string[i]);
   }
 
   printf("%s/n",string);
 
   return 0;
}
 
 
 
函数名: tzset
功 能: UNIX时间兼容函数
用 法: void tzset(void);
程序例:
 
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   time_t td;
 
   putenv("TZ=PST8PDT");
   tzset();
   time(&td);
   printf("Current time = %s/n", asctime(localtime(&td)));
   return 0;
}
 
 
函数名: ultoa
功 能: 转换一个无符号长整型数为字符串
用 法: char *ultoa(unsigned long value, char *string, int radix);
程序例:
 
#include <stdlib.h>
#include <stdio.h>
 
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 <stdio.h>
#include <ctype.h>
 
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 <stdio.h>
#include <ctype.h>
#include <conio.h>
 
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 <stdio.h>
#include <dos.h>
 
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 <stdio.h>
#include <io.h>
 
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 <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <process.h>
#include <share.h>
#include <stdio.h>
 
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;
}
 
 
函数名: vfprintf
功 能: 送格式化输出到一流中
用 法: int vfprintf(FILE *stream, char *format, va_list param);
程序例:
 
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
 
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 <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
 
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 <stdio.h>
#include <stdarg.h>
 
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 <stdio.h>
#include <conio.h>
#include <stdarg.h>
 
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 <stdio.h>
#include <conio.h>
#include <stdarg.h>
 
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 <stdio.h>
#include <conio.h>
#include <stdarg.h>
 
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;
}
 
 
 
函数名: wherex
功 能: 返回窗口内水平光标位置
用 法: int wherex(void);
程序例:
 
#include <conio.h>
 
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 <conio.h>
 
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 <conio.h>
 
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 <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <io.h>
#include <string.h>
 
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;
}
 
原创粉丝点击