函数名: geninterrupt
功 能: 产生一个软中断
用 法: void geninterrupt(int intr_num);
84
程序例:
#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
85
功 能: 取得最后一次调用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, "");
87
/* 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;
}
88
函数名: 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 backgroundcolor.");
/* 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;
}
90
函数名: 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;
}
91
函数名: 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;
}
92
函数名: 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 */
93
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 withform of response: X:\ */
path[0] = 'A' + getdisk(); /* replace X with currentdrive letter */
getcurdir(0, path+3); /* fill rest of string withcurrent directory */
return(path);
}
int main(void)
94
{
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;
95
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;
97
}
函数名: 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);
程序例:
99
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *s;
s=getenv("COMSPEC"); /* get the comspecenvironment 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)
{
100
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;
101
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());
102
/* 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;
103
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 andcolor */
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;
}
104
函数名: 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 outputfile.\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);
程序例:
105
#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 modenumber.", mode);
sprintf(modename, "%s is the current graphicsmode", getmodename(mode));
/* display the information */
settextjustify(CENTER_TEXT, CENTER_TEXT);
106
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;
}
107
函数名: 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 modenumber.", mode);
sprintf(modename, "%s is the current graphicsmode", 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;
109
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 bytesize of image */
for (block=0; block<=3; block++)
110
{
if ((buf[block] = farmalloc(size)) == NULL)
{
closegraph();
printf("Error: not enough heap space insave_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 bytesize
of image */
for (block=0; block<=3; block++)
{
if ((buf[block] = farmalloc(size)) == NULL)
{
closegraph();
printf("Error: not enough heap space insave_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;
112
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 linepattern.", 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;
}
113
函数名: 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 colors0..%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 */
}
115
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 */
116
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 */
117
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 modenumber.", mode);
sprintf(modename, "%s is the current graphicsmode.", 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 \ modifiableentries.", 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);
程序例:
121
#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();
122
/* 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;(;););;; ; ; ; ; ; ; ; ; ; ; ;
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
123
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
;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)
{
124
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 restorescreen...");
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);
125
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;
126
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 textstyle.",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 horizontaljustification.", hjust[textinfo.horiz]);
sprintf(vjuststr, "%s is the verticaljustification.", 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);
127
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 128pointer */
int looping = 1;
int main(void)
{
puts("Press <Shift><Prt Sc> toterminate");
/* 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 ofloop
*/
}
函数名: getverify
功 能: 返回DOS校验标志状态
用 法: int getverify(void);
程序例:
#include <stdio.h>
#include <dos.h>
int main(void)
{
if (getverify())
printf("DOS verify flag is on\n");
129
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;
130
midy = getmaxy() / 2;
/* get information about current viewport */
getviewsettings(&viewinfo);
/* convert text information into strings */
sprintf(topstr, "(%d, %d) is the upper leftviewport corner.", viewinfo.left, viewinfo.top);
sprintf(botstr, "(%d, %d) is the lower rightviewport 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)
{
131
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;
}
132
函数名: 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 */
133
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());
134
/* 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;
}
135
函数名: 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);
程序例:
136
#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 valuesare restored.");
getch();
/* restore default values for everything */
graphdefaults();
/* clear the screen */
cleardevice();
137
/* output line with default settings */
line(0, 0, maxx, maxy);
outtextxy(maxx/2, maxy/3, "After restoringdefault 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));
138
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:");
139
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 graphicsmode:");
getch();
clrscr();
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
140
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 exitgraphics 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 %dbytes.\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 %dbytes.\n", size);
printf("hit any key:");
141
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 graphicsmode:");
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();
142
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 exitgraphics 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 %dbytes.\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 %dbytes.\n", size);
printf("hit any key:");
getch();
printf("\n");
/* free ptr from far heap */
farfree(ptr);
}
143
函数名: 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 diskproblems*/
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;
144
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)
145
{
/* 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 withabort, 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 driveA:\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
146
功 能: 硬件错误处理函数
用 法: void hardresume(int rescode);
程序例:
/* This program will trap disk errors and prompt theuser
for action. */
/* Try running it with no disk in drive A: to invokeits
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 diskproblems
*/
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)
147
{
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 dueto
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;
148
di= _DI;
/* if this is not a disk error then it was anotherdevice
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 withabort,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 probleminterrupt */
harderr(handler);
clrscr();
printf("Make sure there is no disk in driveA:\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;
}
149
函数名: 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 h
用 法: double h
函数名: 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>
152
#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>
153
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 thetext window\r\n");
cprintf("at the cursor position using the currenttext\r\n");
cprintf("background color. All lines below theempty one\r\n");
cprintf("move down one line and the bottom linescrolls\r\n");
cprintf("off the bottom of thewindow.\r\n");
cprintf("\r\nPress any key to continue:");
gotoxy(1, 3);
getch();
insline();
getch();
return 0;
}
154
函数名: 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;
}
155
/* 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>
156
/* 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;
157
/* 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, unionREGS *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, ®s, ®s);
}
int main(void)
{
clrscr();
movetoxy(35, 10);
158
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);
159
程序例:
#include <stdio.h>
#include <dos.h>
/* deletes file name; returns 0 on success, nonzero onfailure */
int delete_file(char near *filename)
{
union REGS regs;
int ret;
regs.h.ah = 0x41; /* delete file */
regs.x.dx = (unsigned) filename;
ret = intdos(®s, ®s);
/* if carry flag is set, there was an error */
return(regs.x.cflag ? ret : 0);
}
int main(void)
{
int err;
err = delete_file("NOTEXIST.$$$");
if (!err)
printf("Able to delete NOTEXIST.$$$\n");
else
printf("Not Able to delete NOTEXIST.$$$\n");
return 0;
}
函数名: intdosx
功 能: 通用DOS中断接口
用 法: int intdosx(union REGS *inregs, union REGS *outregs,struct SREGS *segregs);
程序例:
#include <stdio.h>
#include <dos.h>
/* deletes file name; returns 0 on success, nonzero onfailure */
int delete_file(char far *filename)
{
union REGS regs;
struct SREGS sregs;
int ret;
regs.h.ah = 0x41; /* delete file */
regs.x.dx = FP_OFF(filename);
sregs.ds = FP_SEG(filename);
ret = intdosx(®s, ®s, &sregs);
/* if carry flag is set, there was an error */
return(regs.x.cflag ? ret : 0);
}
int main(void)
{
int err;
err = delete_file("NOTEXIST.$$$");
if (!err)
printf("Able to delete NOTEXIST.$$$\n");
else
printf("Not Able to delete NOTEXIST.$$$\n");
return 0;
}
函数名: intr
功 能: 改变软中断接口
用 法: void intr(int intr_num, struct REGPACK *preg);
程序例:
#include <stdio.h>
#include <string.h>
#include <dir.h>
#include <dos.h>
#define CF 1 /* Carry flag */
int main(void)
161
{
char directory[80];
struct REGPACK reg;
printf("Enter directory to change to: ");
gets(directory);
reg.r_ax = 0x3B << 8; /* shift 3Bh into AH */
reg.r_dx = FP_OFF(directory);
reg.r_ds = FP_SEG(directory);
intr(0x21, ®);
if (reg.r_flags & CF)
printf("Directory change failed\n");
getcwd(directory, 80);
printf("The current directory is: %s\n",directory);
return 0;
}
函数名: ioctl
功 能: 控制I/O设备
用 法: int ioctl(int handle, int cmd[,int *argdx, intargcx]);
程序例:
#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;
}
162
函数名: isatty
功 能: 检查设备类型
用 法: int isatty(int handle);
程序例:
#include <stdio.h>
#include <io.h>
int main(void)
{
int handle;
int handle;
函数名: 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
163
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;
164
/* call the old interrupt handler */
oldhandler();
}
int main(void)
{
/* get the address of the current clock
tick interrupt */
oldhandler = getvect(INTR);
/* install the new interrupt handler */
setvect(INTR, handler);
/* _psp is the starting address of the
program in memory. The top of the stack
is the end of the program. Using _SS and
_SP together we can get the end of the
stack. You may want to allow a bit of
saftey space to insure that enough room
is being allocated ie:
(_SS + ((_SP + safety space)/16) - _psp)
*/
keep(0, (_SS + (_SP/16) - _psp));
return 0;
}
L
函数名: labs
功 能: 取长整型绝对值
用 法: long labs(long n);
程序例:
#include <stdio.h>
#include <math.h>
int main(void)
{
165
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);
程序例:
166
/* 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);
168
}
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));
169
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;
170
/* 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);
171
}
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;
}
172
函数名: 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;
173
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;
}
174
函数名: 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;
}
M
main()主函数
每一C 程序都必须有一main()函数, 可以根据自己的爱好把它放在程序的某个地方。有些程序员把它放在最前面, 而另一些程序员把它放在最后面, 无论放在哪个地方, 以下几点说明都是适合的。
1. main() 参数
在Turbo C2.0 启动过程中, 传递main()函数三个参数: argc,argv 和env。
* argc: 整数, 为传给main()的命令行参数个数。
* argv: 字符串数组。
在DOS 3.X 版本中, argv[0] 为程序运行的全路径名; 对DOS 3.0以下的版本,argv[0]为空串("") 。
argv[1] 为在DOS命令行中执行程序名后的第一个字符串;
argv[2] 为执行程序名后的第二个字符串;
...
argv[argc]为NULL。
*env: 安符串数组。env[] 的每一个元素都包含ENVVAR=value形式的字符串。其中ENVVAR为环境变量如PATH或87。value 为ENVVAR的对应值如C:\DOS, C:\TURBOC(对于PATH) 或YES(对于87)。
Turbo C2.0 启动时总是把这三个参数传递给main()函数, 可以在用户程序中说明(或不说明)它们, 如果说明了部分(或全部)参数, 它们就成为main()子程序的局部变量。
请注意: 一旦想说明这些参数, 则必须按argc, argv, env 的顺序, 如以下的例子:
main()
main(int argc)
main(int argc, char *argv[])
main(int argc, char *argv[], char *env[])
其中第二种情况是合法的, 但不常见, 因为在程序中很少有只用
argc, 而不
用argv[]的情况。
以下提供一样例程序EXAMPLE.EXE, 演示如何在main()函数中使
用三个参数:
/*program name EXAMPLE.EXE*/
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[], char *env[])
{
int i;
printf("These are the %d command- line argumentspassed 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 systemare:\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 withblanks" 3 4
"last but
one" stop!
178
注意: 可以用双引号括起内含空格的参数, 如本例中的: "
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 thatprevents
any error messages from being printed. */
#include<math.h>
int matherr(struct exception *a)
{
return 1;
}
179
函数名: 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>
180
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 allocatebuffer\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");
181
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>
182
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, unsignedn);
程序例:
#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);
183
程序例:
#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)
{
185
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);
186
程序例:
#include <mem.h>
#define MONO_BASE 0xB000
/* saves the contents of the monochrome screen inbuffer */
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();
187
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, intbottom, 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();
189
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);
191
程序例:
/* Emits a 7-Hz tone for 10 seconds.
True story: 7 Hz is the resonant frequency of achicken's
skull cavity.
This was determined empirically in Australia, where anew
factory
generating 7-Hz tones was located too close to achicken
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();
}
O
函数名: 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";
192
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>
193
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 */
}
194
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 */
195
{
printf("Graphics error:%s\n",grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(1); /* terminate with an error code */
}
midx = getmaxx() / 2;
midy = getmaxy() / 2;
/* output text at the center of the screen*/
/* Note: the C.P. doesn't get changed.*/
outtextxy(midx, midy, "This is a test.");
/* clean up */
getch();
closegraph();
return 0;
}
P
函数名: parsfnm
功 能: 分析文件名
用 法: char *parsfnm (char *cmdline, struct fcb *fcbptr, intoption);
程序例:
#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 keyboardis:\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");
197
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;
198
printf("The current status of your keyboardis:\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;
}
199
函数名: 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, "");
200
/* 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 andpress any key\r\n");
getch();
poke(0x0000,0x0417,16);
cprintf("The scroll lock is now on\r\n");
201
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 andpress 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;
202
result = poly(2.0, 3, array);
printf("The polynomial: x**3 - 2.0x**2 + 5x - 1at 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;
}
203
函数名: 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,"");
204
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);
205
程序例:
#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++)
206
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;
207
/* 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, intop);
程序例:
#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;
208
/* 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;
210
/* 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);
}
211
}
/* clean up */
getch();
closegraph();
return 0;
}
函数名: puts
功 能: 送一字符串到流中
用 法: int puts(char *string);
程序例:
#include <stdio.h>
int main(void)
{
char string[] = "This is an example outputstring\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 tocontinue ...");
212
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))
213
printf("Error writing to file\n");
else
printf("Successful write\n");
fclose(fp);
/* reopen the file */
fp = fopen(FNAME, "rb");
if (fp == NULL)
{
printf("Error opening file %s\n", FNAME);
exit(1);
}
/* extract the word */
word = getw(fp);
if (ferror(fp))
printf("Error reading file\n");
else
printf("Successful read: word = %d\n",word);
/* clean up */
fclose(fp);
unlink(FNAME);
return 0;
}
Q
函数名: 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);
214
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) );
}
R
函数名: 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;
215
}
函数名: rand
功 能: 随机数发生器
用 法: void rand(void);
程序例:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
printf("Ten random numbers from 0 to99\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;
216
/* 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);
217
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();
218
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)
{
219
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 to99\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>
220
int main(void)
{
void *buf;
int handle, bytes;
buf = malloc(10);
/*
Looks for a file in the current directory namedTEST.$$$
and attempts
to read 10 bytes from it. To use this example youshould
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>
221
#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, intbottom);
程序例:
#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 */
223
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
功 能: 删除一个文件
224
用 法: 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);
225
/* 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;
226
y = getmaxy() / 2;
/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "Press any key to exitgraphics:");
getch();
/* restore system to text mode */
restorecrtmode();
printf("We're now in text mode.\n");
printf("Press any key to return to graphicsmode:");
getch();
/* return to graphics mode */
setgraphmode(getgraphmode());
/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "We're back in graphicsmode.");
outtextxy(x, y+textheight("W"), "Pressany 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;
227
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");
228
getch();
stat = rmdir(DIRNAME);
if (!stat)
printf("\nDirectory deleted\n");
else
{
perror("\nUnable to delete directory\n");
exit(1);
}
return 0;
}
函数名: 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;
}
229
函数名: rand
功 能: 随机数发生器
用 法: void rand(void);
程序例:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
printf("Ten random numbers from 0 to99\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);
230
/* 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;
}
231
函数名: 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;
232
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;
233
}
函数名: 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 to99\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;
234
int handle, bytes;
buf = malloc(10);
/*
Looks for a file in the current directory namedTEST.$$$
and attempts
to read 10 bytes from it. To use this example youshould
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)
{
235
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, intbottom);
程序例:
#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();
236
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);
237
/* 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>
238
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");
239
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 exitgraphics:");
240
getch();
/* restore system to text mode */
restorecrtmode();
printf("We're now in text mode.\n");
printf("Press any key to return to graphicsmode:");
getch();
/* return to graphics mode */
setgraphmode(getgraphmode());
/* output a message */
settextjustify(CENTER_TEXT, CENTER_TEXT);
outtextxy(x, y, "We're back in graphicsmode.");
outtextxy(x, y+textheight("W"), "Pressany 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);
241
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");
242
else
{
perror("\nUnable to delete directory\n");
exit(1);
}
return 0;
}
S
函数名: 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 bytesfree\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>
243
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 restrictingto 20 characters */
printf("\n\nPlease enter a label for the chart:");
scanf("%20s", label);
fflush(stdin); /* flush the input stream in case ofbad input */
/* Input number of entries as an integer */
printf("How many entries will there be? (lessthan 20) ");
scanf("%d", &entries);
fflush(stdin); /* flush the input stream in case ofbad input */
/* input a name restricting input to only lettersupper 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 ofbad input */
/* input an age as an integer */
printf(" Age : ");
scanf("%d", &entry[loop].age);
244
fflush(stdin); /* flush the input stream in case ofbad input */
/* input a salary as a float */
printf(" Salary : ");
scanf("%f", &entry[loop].salary);
fflush(stdin); /* flush the input stream in case ofbad input */
}
/* Input a name, age and salary as a string, integer,and double */
printf("\nPlease enter your name, age andsalary\n");
scanf("%20s %d %lf", name, &age,&salary);
/* Print out the data that was input */
printf("\n\nTable %s\n",label);
printf("Compiled by %s age %d $%15.2lf\n",name, age, salary);
printf("-----------------------------------------------------\n");
for (loop=0;loop<entries;++loop)
printf("%4d | %-20s | %5d | %15.2lf\n", loop+ 1, entry[loop].name, entry[loop].age, entry[loop].salary);
printf("-----------------------------------------------------\n");
return 0;
}
函数名: searchpath
功 能: 搜索DOS路径
用 法: char *searchpath(char *filename);
程序例:
#include <stdio.h>
#include <dir.h>
245
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, intendangle);
程序例:
#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 */
246
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 registersettings\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 */
}
248
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 tohalt:");
/* 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>
249
#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 */
250
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 */
251
{
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
功 能: 用调色板设置当前背景颜色
252
用 法: 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 */
253
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 paragraphsavailable 254 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 paragraphsavailable is %d\n", stat);
freemem(segp); <b
freemem(segp); <b
函数名: 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);
程序例:
255
#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));
256
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)
{
257
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
258
功 能: 返回以像素为单位的字符串高度
用 法: 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);
259
/* 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();
260
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++)
261
{
/* 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;
}
262
函数名: 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);
263
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>
264
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;
}
U
函数名: ultoa
功 能: 转换一个无符号长整型数为字符串
用 法: char *ultoa(unsigned long value, char *string, intradix);
程序例:
#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 achar:");
/* read chars until non digit or EOF */
266
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 achar:");
/* 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());
267
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 ofseconds
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 ofseconds
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 */
268
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;
}
269
函数名: 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
270
printf("unlock failed\n");
close(handle);
return 0;
}
V
函数名: vfprintf
功 能: 送格式化输出到一流中
用 法: int vfprintf(FILE *stream, char *format, va_listparam);
程序例:
#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)
函数名: wherex
功 能: 返回窗口内水平光标位置
用 法: int wherex(void);
程序例:
#include <conio.h>
271
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, intbottom);
程序例:
272
#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 thecurrent directory
and write
a string to it. If "TEST.$$$" alreadyexists, it will be
overwritten.
*/
273
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;
}
屏幕函数
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是指光标要定位处的坐标(相对于窗口
278
而言), 当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()函数中的坐标是对整个屏幕而言的,
即是屏幕的绝对坐标,