C function library Daquan 2

xiaoxiao2021-03-06  53

Function Name: QSORT function: Sort by rapid sort routine: Void Qsort (Void * Base, int NELEM, INT WIDTH, INT (* FCMP) ());

#include

#include

#include

INT Sort_function (const void * a, const void * b);

Char List [5] [4] = {"Cat", "Car", "CAB", "CAP", "CAN"}

INT main (void) {INT X;

Qsort ((void *) list, 5, sizeof (List [0]), sort_function; for (x = 0; x <5; x ) Printf ("% s / n", list [x]); return 0 }

Int sort_function (const void * a, const void * b) {return (strcmp (a, b));}

Function Name: QSORT function: Sort by rapid sort routine: Void Qsort (Void * Base, int NELEM, INT WIDTH, INT (* FCMP) ());

#include

#include

#include

INT Sort_function (const void * a, const void * b);

Char List [5] [4] = {"Cat", "Car", "CAB", "CAP", "CAN"}

INT main (void) {INT X;

Qsort ((void *) list, 5, sizeof (List [0]), sort_function; for (x = 0; x <5; x ) Printf ("% s / n", list [x]); return 0 }

Int sort_function (const void * a, const void * b) {return (strcmp (a, b));}

Function Name: RAISE Features: Send a signal usage to the executable program: int RAISE (INT SIG);

#include

INT main (void) {Int A, B;

A = 10; b = 0; if (b == 0) / * preempt divide by zero error * / raise (sigfpe); A = a / b; return 0;}

Function name: RAND function: random number generator usage: Void Rand (Void);

#include

#include

INT main (void) {INT I;

Printf ("Ten Random Numbers from 0 to 99 / N / N"); for (i = 0; I <10; I ) Printf ("% D / N", RAND ()% 100); Return 0;}

Function Name: Randbrd Features: Random Block Reading: Int Randbrd (Struct FCB * Fcbptr, INT Reccnt);

#include

#include

#include

#include

INT main (void) {char far * save_dta; char line [80], buffer [256]; structure fcb blk; int i, result;

/ * GET User Input File Name for DTA * / 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)) {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;}

Function Name: RandbWR Function: Random Block Writing: Int RandbWr (Struct FCP * FCBPTR, INT Reccnt);

#include

#include

#include

#include

INT main (void) {char far * save_dta; char line [80]; char buffer [256] = "Randbwr Test!"; structure fcb blk; int result;

/ * Get new file name from user * / printf ("Enter a file name to create (no path - ie. A: file.dat / n"); gets (line);

/ * PARSE The New File Name to the DTA * / PARSFNM (Line, & BLK, 1); Printf ("DRIVE #% D File:% S / N", BLK.FCB_DRIVE, BLK.FCB_NAME);

/ * Request dos Services to create file * / if (BDoSPTR (0x16, & BLK, 0) == -1) {Perror ("Error Creating File"); exit (1);

/ * Save Old DTA and Set New DTA * / Save_DTA = getdta (); setdta (buffer);

/ * Write new records * / blk.fcb_recsize = 256; BLK.FCB_RAndOM = 0L; Result = randbwr (& BLK, 1); if (! Result) Printf ("Write OK / N"); else {PERROR ("Disk error "); exit (1);

/ * Request DOS Services to Close To File * / IF (BDOSPTR (0x10, & BLK, 0) == -1) {Perror ("Error Closing File"); EXIT (1);}

/ * RESET the OLD DTA * / SETDTA (Save_DTA);

Return 0;}

Function Name: Random Features: Random Number Generator Usage: Int Random (INT NUM);

#include

#include

#include

/ * Prints a Random Number in the Range 0 to 99 * / int main (void) {randomize (); Printf ("Random Number in the 0-99 Range:% D / N", Random (100)); Return 0 }

Function Name: Randomize Features: Initialization Random Random Generator Usage: Void Randomize (Void);

#include

#include

#include

INT main (void) {INT I;

Randomize (); Printf ("Ten Random Numbers FROM 0 to 99 / N / N"); for (i = 0; I <10; I ) Printf ("% D / N", RAND ()% 100); Return }

Function Name: Read function: Reading from the file: int tent (int tent, void * buf, int nbyte);

#include

#include

#include

#include

#include

#include

INT main (void) {void * buf; int handle, bytes;

BUF = Malloc (10);

/ * Looks for a file in the capital Directory named Test. $$$ and attempts to read 10 bytes from it. To use this example you shouth create the file test. $$$ * / if ((Handle = Open) $$$, 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 ("}) n ", bytes);} return 0;}

Function Name: Realloc Features: Renotes Main Deposit: Void * Realloc (VOID * PTR, Unsigned Newsize);

#include

#include

#include

INT main (void) {char * str; / * allocate memory for string * / str = malloc (10);

/ * Copy "Hello" INTO STRING * / STRCPY (STR, "Hello");

Printf ("String IS% S / N Address IS% P / N", STR, STR); Str = Realloc (STR, 20); Printf ("String IS% S / N New Address IS% P / N", STR STR);

/ * free memory * / free (str);

Return 0;}

Function name: Rectangle function: draw a rectangular usage: Void Far Rectangle (int LEFT, INT TOP, INT RIGHT, INT BOTTOM);

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, errorcode; int LEFT, TOP, RIGHT, BOTTOM

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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);

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function Name: RegisterBgidriver Features: Log in to the Connected Graphics Driver Code Usage: int RegisterBgidriver (Void (void));

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, erroorcode

/ * 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 results = graphresult (); if (error (error) / * an error opcurred * / {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 ());

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function Name: Remove Features: Delete a file usage: int Remove (Char * filename);

#include

INT main (void) {char file [80];

/ * Prompt for file name to delete * / printf ("File to delete:"); gets (file);

/ * delete the file * / if (remote (file) == 0) Printf ("Removed% s. / n", file); Else Perror ("remove");

Return 0;}

Function Name: Rename Features: Rename File Usage: int Rename (Char * OldName, Char * NewName);

#include

INT main (void) {char {company [80], newname [80];

/ * Prompt for file to rename and new name * / printf ("File to Rename:"); Gets (OldName); Printf ("New Name:"); gets (newname);

/ * Rename the file * / if (Rename (OldName, NewName) == 0) Printf ("Renamed% S TO% s. / N", OldName, NewName); Else Perror ("Rename");

Return 0;}

Function Name: RESTORECRTMODE function: Restoring the screen mode to the previous ImitGraph Setting: Void Far RestoreCrtMode (Void);

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, erroorcode; 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", GraphherrorMSG (ErrorCode)); Printf ("Press Any Key to Halt:"); getCh (); exit (1); / * Terminate with an error code * /}

x = getmaxx () / 2; y = getmaxy () / 2;

/ * Output a message * / settextjustify (center_text, center_text); OutTextxy (x, y, "press any key to exit graphics:"); getch ();

/ * RESTORE SYSTEM to TEXT MODE * / RESTORECRTMODE (); Printf ("We're now in text mode./N); Printf (" Press any key to return to graphics mode: "); getch ();

/ * return to graphics mode * / setgraphmode (getgraphmode ());

/ * OUTPUT A Message * / setTextJustify (center_text, center_text); OutTextxy (x, y, "We're Back in graphics mode."); Outtextxy (x, y textheight ("W"), "Press Any Key To HALT: ");

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function Name: ReWind function: Redirect the file pointer to a stream: int Rewind (file * stream);

#include

#include

INT main (void) {file * fp; char * fname = "txxxxxx", * newname, first;

NEWNAME = MkTemp (FP = FOPEN); FPRINTF (FP, "AbcdefghijklmnopQrstuvwxyz"); ReWind (fp); FSCANF (FP, "% C", & first); Printf ("THE FIRST CHARACTER IS:% C / N ", First); Fclose (FP); Remove (newname);

Return 0;}

Function name: RMDIR function: Delete DOS file directory usage: int RMDIR (Char * stream);

#include

#include

#include

#include

#define dirname "Testdir. $$$"

INT main (void) {int stat;

Stat = mkdir; if (! stat) Printf ("Directory Created / N"); Else {Printf ("Unable to create Directory / N); exit (1);} getCH (); system (" DIR / P "); getCH ();

Stat = rmdir; if (! stat) printf ("/ ndirectory deleted / n"); else {PERROR ("/ NUNABLE to DELETE DIRECTORY / N); EXIT (1);

Return 0;}

Function name: PARSFNM function: Analysis file name usage: char * PARSFNM (Char * cmdline, struct fcb * fcbptr, int option);

#include

#include

#include

#include

INT main (void) {char line [80]; structure 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;}

Function Name: PEEK Features: Check storage unit usage: int peek (int segment, unsigned offset);

#include

#include

#include

INT main (void) {int value = 0;

Printf ("THE CURRENT Status of Your Keyboard IS: / N"); Value = Peek (0x0040, 0x0017); if (Value & 1) Printf ("Right Shift ON / N"); Else Printf ("Right Shift OFF / n ");

IF (Value & 2) Printf ("Left Shift ON / N"); Else Printf ("Left Shift Off / N");

IF (Value & 4) Printf ("Control Key ON / N"); Else Printf ("Control Key Off / N");

IF (Value & 8) Printf ("Alt Key ON / N"); Else Printf ("Alt Key Off / N");

IF (Value & 16) Printf ("Scroll Lock ON / N"); Else Printf ("Scroll Lock Off / N");

IF (Value & 32) Printf ("NUM LOCK ON / N"); Else Printf ("Num Lock Off / N");

IF (Value & 64) Printf ("Caps Lock ON / N"); Else Printf ("Caps Lock Off / N");

Return 0;}

Function Name: Peekb Fenergy: Check the storage unit usage: Char Peekb (int segment, unsigned offset);

#include

#include

#include

INT main (void) {int value = 0;

Printf ("THE CURRENT Status of Your Keyboard IS: / N"); Value = peekb (0x0040, 0x0017); if (Value & 1) Printf ("Right Shift ON / N"); Else Printf ("Right Shift OFF / N ");

IF (Value & 2) Printf ("Left Shift ON / N"); Else Printf ("Left Shift Off / N");

IF (Value & 4) Printf ("Control Key ON / N"); Else Printf ("Control Key Off / N");

IF (Value & 8) Printf ("Alt Key ON / N"); Else Printf ("Alt Key Off / N");

IF (Value & 16) Printf ("Scroll Lock ON / N"); Else Printf ("Scroll Lock Off / N");

IF (Value & 32) Printf ("NUM LOCK ON / N"); Else Printf ("Num Lock Off / N");

IF (Value & 64) Printf ("Caps Lock ON / N"); Else Printf ("Caps Lock Off / N");

Return 0;}

Function Name: PERROR Energy: System Error Information Usage: Void Perror (Char * String);

#include

INT main (void) {file * fp;

FP = fopen ("PERROR.DAT", "R"); if (! fp) PERROR ("Unable to open file forreading"; return 0;}

Function Name: Piemelice Features: Draw and populate a sector: Void Far PiemeLice (int X, int stanle, int endangle, int RADIUS);

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, errorcode; int midx, midy; int standle = 45, endangle = 135, radius = 100;

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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 ()); Piemelice (MIDX, Midy, Stangle, Endangle, RADIUS)

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function Name: Poke function: save a given storage unit usage: void poke (int segment, int offset, int value);

#include

#include

INT main (void) {clrs (); CPRINTF ("Make Sure Scroll Lock Key IS Off and Press Any Key / R / N"); getCh (); Poke (0x0000, 0x0417, 16); CPrintf ("The scroll Lock is now on / r / n "); Return 0;}

Function Name: Pokeb Features: A value to a given storage unit: Void pokeb (int segment, int offset, char value);

#include

#include

INT main (void) {clrs (CPRINTF ("Make Sure Scroll Lock Key IS Off and Press Any Key / R / N"); getCh (); pokeb (0x000000000000000000, 0x0417, 16); CPrintf ("the scroll Lock is now on / r / n "); Return 0;}

Function name: Poly function: Generate a polynomial usage based on parameters: Double Poly (Double X, INT N, DOUBLE C []);

#include

#include

/ * POLYNOMIAL: X ** 3 - 2X ** 2 5X - 1 * /

INT main (void) {double array [] = {-1.0, 5.0, -2.0, 1.0}; Double Result

Result = poly (2.0, 3, array); Printf ("The Polynomial: x ** 3 - 2.0x ** 2 5X - 1 AT 2.0 IS% LF / N", Result); Return 0;}

Function Name: Pow Function: Index Function (X of X) Usage: Double Pow (Double X, Double Y);

#include

#include

INT main (void) {double x = 2.0, y = 3.0;

Printf ("% lf raised to% LF IS% LF / N", X, Y, POW (X, Y)); Return 0;}

Function Name: POW10 Function: Index Function (10 P - Party) Usage: Double Pow10 (INT P); Project: #include

#include

INT main (void) {double p = 3.0;

Printf ("Ten Raised TO% LF IS% LF / N", P, POW10 (P)); Return 0;}

Function Name: Printf function: Function usage of formatted output: int printf (char * format ...);

#include

#include

#define i 555 #define r 5.5

INT main (void) {INT I, J, K, L; Char BUF [7]; char * prefix = buf; char TP [20]; Printf ("prefix 6d 6o 8x 10.2e" "10.2f / n") ; strcpy (prefix, "%"); for (i = 0; i <2; i ) {for (j = 0; j <2; j ) for (k = 0; k <2; k ) for (L = 0; L <2; L ) {IF (i == 0) STRCAT (prefix, "-"); if (j == 0) STRCAT (Prefix, " "); if (k == 0) STRCAT (Prefix, "#"); if (l == 0) STRCAT (Prefix, "0"); Printf ("% 5s |", prefix); strcpy (tp, prefix); strcat (TP, "6D |" PRINTF (TP, I); STRCPY (TP, "); STRCPY (TP, Prefix); STRCAT (TP," 6O | "); Printf (TP, I); STRCPY (TP,"); STRCPY (TP, Prefix); STRCAT (TP, "8x |"); Printf (TP, I); STRCPY (TP, "); STRCPY (TP, Prefix); STRCAT (TP," 10.2e | "); Printf (TP, R); STRCPY (TP, Prefix); STRCAT (TP, "10.2F |"); Printf (TP, R); Printf ("/ n"); strcpy (prefix, "%");}} Return 0;}

Function Name: PUTC function: Output a character to the specified stream Usage: int PUTC (INT CH, File * Stream);

#include

INT main (void) {char msg [] = "Hello World / N"; int i = 0;

While (MSG [i]) PUTC (MSG [i ], stdout; return 0;}

Function Name: PUTCH Function: Output Character to Console Usage: Int Putch (INTCH);

#include

#include

INT main (void) {char ch = 0;

Printf ("INPUT A String:"); While ((ch! = '/ r')) {ch = getCH (); PUTCH (CH);} return 0;}

Function Name: PUTCHAR Function: Output Character Usage on STDOUT: Int Putchar (Int Ch); Procedure: #include

/ * Define Some Box-Drawing Characters * / #define Left_top 0xDa #define Right_top 0xBF #define horiz 0xc4 #define Vert 0xB3 #define LEFT_BOT 0XC0 #define Right_Bot 0xD9

Int main (void) {char i, j;

/ * Draw the top of the box * / putchar (left_top); for (i = 0; i <10; i ) PUTCHAR (HORZ); 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;}

Function name: Putenv function: add string to the current environment: int putenv (char * envvar);

#include

#include

#include

#include

#include

INT main (void) {char * path, * ptr; int i = 0;

/ * get the current path environment * / ptr = getenv ("path");

/ * SET UP new path * / path = malloc (Strlen (PTR) 15); STRCPY (PATH, "PATH ="); strcat (PTH, 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;}

Function Name: PUTIMAGE function: Output a bitmap usage on the screen: Void Far Putimage (INT X, INT Y, VOID FAR * BITMAP, INTOP);

#include

#include

#include

#include

#define arrow_size 10

Void Draw_arrow (int X, int y);

INT main (void) {/ * request autodtection * / int gDriver = detect, gmode, errorcode; void * arrow; int x, y, maxx; unsigned int size;

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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 isperat * / 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); lineerel (4 * arrow_size, 0); lineerel (-2 * arrow_size, -1 * arrow_size); LineRel (0, 2 * arrow_size); LineRel (2 * arrow_size, -1 * arrow_size);}

Function Name: PUTPIEL function: Draw a pixel usage in the specified location: Void Far Putpixel (int X, int y, int pixelcolor);

#include

#include

#include

#include

#include

#define pixel_count 1000 #define delay_time 100 / * in MilliseConds * /

INT main (void) {/ * request autodtection * / int gDriver = detect, gmode, errorcode; int i, x, y, color, maxx, maxy, maxcolor, seed;

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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 ()) {/ * seeded = random (32767); SRAND (seed); for (i = 0; i

{

X = random (maxx);

Y = random (MAXY);

Color = random (maxcolor);

PUTPIXEL (X, Y, Color);

}

DELAY (DELAY_TIME); SRAND (SEED); for (i = 0; i

{

X = random (maxx);

Y = random (MAXY);

Color = random (maxcolor);

IF (color == getpixel (x, y))

Putpixel (x, y, 0);

}

}

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function name: PUTS function: send a string to the stream Usage: int Puts (char * string);

#include

Int main (void)

{

Char string [] = "this is an example output string / n";

PUTS (String); Return 0;

Function name: PutText function: copy text from the storage area to the screen usage: int PutText (int LEFT, INT TOP, INT Right, int bottom, void * source);

#include

Int main (void)

{

Char buffer [512];

/ * Put Some text to the console * / clrs (); gotoxy (20, 12); CPRINTF ("this is a test. press any key to pay ..."); getch ();

/ * GRAB Screen Contents * / GetText (20, 12, 36, 21, Buffer; CLRSCR ();

/ * Put Selected Characters Back to the screen * / gotox t (20, 12); PUTTEXT (20, 12, 36, 21, buffer); getCh ();

Return 0;}

Function Name: PUTW function: send a character or word to the stream: int PUTW (int W, file * stream);

#include

#include

#define fname "Test. $$$"

INT main (void) {file * fp; int word;

/ * Place the Word IN A file * / fp = fopen (FNAME, "WB"); if (fp == null) {Printf ("Error Opening File% S / N", FNAME); EXIT (1); Word = 94; PUTW (Word, FP); IF (FERROR (FP)) Printf ("Error Writing to File / N); Else Printf (" Successful Write / N "); Fclose (FP);

/ * Reopen the file * / fp = fopen (fname, "rb"); if (fp == null) {Printf ("Error Opening File% S / N", FNAME); Exit (1);

/ * Extract the word * / word = getw (fp); if (FERROR (FP)) Printf ("Error Reading File / N"); Else Printf ("Successful Read: Word =% D / N", WORD);

/ * Clean Up * / fclose (fp); unlink (fname);

Return 0;}

Void NormVideo (Void); Select the normal brightness character. Set the text attribute (foreground and background) to the value when it starts the program to select a standard character.

Void Noid (Void); Close the speaker that is invoked by calling Sound.

Function Name: Open function: Open a file for reading or writing: int open (char * pathname, int access [, int permiss);

#include

#include

#include

#include

INT main (void) {Int Handle; char msg [] = "Hello World";

IF ("Test. $$$", O_CREAT | O_TEXT)) == -1) {Perror ("Error:"); Return 1;} Write (Handle, MSG, Strlen (MSG)); Close (Handle); Return 0;

Function Name: OUTPORT Features: Output Integer to Hardware Port Usage: Void Outport (Int Port, Int Value);

#include

#include

INT main (void) {int value = 64; int port = 0;

OUTPORTB (Port, Value); Printf ("Value% D Sent To Port Number% D / N", Value, Port); Return 0;

Function Name: Outportb Features: Output bytes to Hardware Port Usage: Void Outportb (Int port, char Byte);

#include

#include

INT main (void) {int value = 64; int port = 0;

OUTPORTB (Port, Value); Printf ("Value% D Sent To Port Number% D / N", Value, Port); Return 0;

Function name: OutText function: display a string usage in the view: Void Far OutText (Char far * text 4;): #include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, erroorcode; int midx, midy

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {printf ("Graphics Error:% S / N", GrapherrorMSG (ErrorCode)); Printf (" Press any key to halt: "); getCH (); exit (1); / * Terminate with an error code * /}

MIDX = getmaxx () / 2; Midy = getMaxy () / 2;

/ * move the c.p. to the center of the screen * / moveto (midx, midy);

/ * Output text starting at the c.p. * / outtext ("this"); OutText ("IS"); OUTTEXT ("a"); OutText ("Test.");

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function Name: OutTextxy function: Display a string usage in the specified location: Void Far Outtextxy (int X, int y, char * textstring);

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, erroorcode; int midx, midy

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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 change. * / Outtextxy (MIDX, MIDY, "This Is A Test.");

/ * Clean Up * / getch (); closegraph (); return 0;} main () master Each C program must have a main () function, you can put it in a place in the program according to your hobby. Some of the programmers put it in front, while others put it in the end, no matter which place, the following description is suitable. 1. Main () parameter During the Turbo C2.0 startup process, pass the main () function three parameters: Argc, Argv, and ENV. * Argc: integer, for the number of command line parameters transmitted to main (). * Argv: string array. In the DOS 3.x version, Argv [0] is a full path name running; a version of DOS 3.0 or less, Argv [0] is an empty string ("). Argv [1] is the first string after executing the program name in the DOS command line; Argv [2] is the second string after executing the program; ... Argv [Argc] is NULL. * ENV: An array array. Each element of ENV [] includes a string in the form of envvar = value. Where ENVVAR is environment variable such as PATH or 87. Value is the correspondence value of Envvar as C: / DOS, C: / Turboc (for PATH) or YES (for 87). Turbo C2.0 always passes these three parameters to the main () function, which can be described (or not) in the user program, if some (or all) parameters are described, they become main () Local variable of the program. Note: Once you want to explain these parameters, you must press the order of Argc, Argv, ENV, as follows: Main () main (int Argc) main (int Argc, char * argv []) main (int Argc, char * Argv [], char * ENV []) The second case is legal, but not common, because there are very few only ARGCs in the program without the case of Argv []. The following example Example.exe is provided, demonstrate how to use three parameters in the main () function: / * program name esample.exe * / #include

#include

Main (int Argc, char * argv [], char * env [])

{

INT I;

Printf ("" THESE ARE The% D Command- line arguments passed to

Main: / n / n ", argc);

For (i = 0; i <= argc; i )

Printf ("Argv [% D]:% S / N", I, ARGV [I]);

Printf ("/ NThe Environment String (S) on this system is: / n / n");

For (i = 0; ENV [i]! = null; i )

Printf ("ENV [% D]:% S / N", I, ENV [i]);

}

If you run an Example.exe: C: / Example First_argument "ARgument with Blanks" 3 4 "Last But One" Stop! Note: You can include a double quotation parameter with double quotes, such as this In the example: "Argument with Blanks" and "Last But One"). The result is: The value of argc is 7 trurbo/example.exe argv [1]: first_argument argv [1]: first_argument argv [1]: first_argument 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 area: env [0]: COMSPEC = C: /command.com env [1]: prompt = $ p $ g / * depending on the specific settings * / ENV [2]: Path = C: / DOS; C: / TC / * terms depending on the settings Type * / should be reminded that the maximum length of the command line parameter of the transfer main () function is 128 characters (including space between parameters), which is limited by DOS. Function Name: MatherR Function: Mathematical Error Handler Method for User Changes: Int Matherr (Struct Exception * E);

/ * This is a user-defined Matherr Function That Prevents Any Error Messages from Being Printed. * /

#include

Int matherr (struct exception * a) {return 1;}

Function Name: Memccpy Features: Copy N bytes from Source Source to Target Destin Usage: Void * Memccpy (Void * Destin, Void * Source, unsigned char ch, unsigned n);

#include

#include

INT main (void) {char * src = "this is the source string"; char DEST [50]; char * PTR;

PTR = Memccpy (DEST, SRC, 'C', STRLEN (SRC));

IF (PTR) {* PTR = '/ 0'; Printf ("THE Character Was Found:% S / N", DEST);} else printf ("THE Character Wasn't Found / N); Return 0;}

Function Name: Malloc Function: Memory Assignment Function Usage: Void * Malloc (Unsigned Size);

#include

#include

#include

#include

INT main (void) {char * STR;

/ * allocate memory for string * / / * this will generate an error when information * / / / * with C , use the new operator instead. * / if ((str = malloc (10)) == null) {printf (" NOT ENOUGH MEMORY TO Allocate Buffer / N "); Exit (1); / * Terminate Program if out of memory * /} / * Copy" Hello "INTO STRING * / STRCPY (STR," Hello ");

/ * Display string * / printf ("String IS% S / N", STR);

/ * free memory * / free (str);

Return 0;}

Function Name: Memchr Features: Search Character Usage in the Pre-N bytes of Arrse: Void * Memchr (Void * S, Char Ch, UNSIGNED N);

#include

#include

INT main (void) {char str [17]; char * PTR;

STRCPY (STR, "this is a string"); PTR = Memchr (STR, 'R', Strlen (STR)); if (PTR) Printf ("The Character 'R' Is At Position:% D / N", PTR - STR); Else Printf ("THE Character Was Not Found / N); Return 0;}

Function Name: Memcpy Features: Copy N bytes from Source Source to Target Destin Usage: Void * Memcpy (Void * Destin, Void * Source, Unsigned N);

#include

#include

Int main (void)

{

Char src [] = "******************************"

CHAR DEST [] = "AbcdefghijlkmnopqrStuvwxyz0123456709";

Char * PTR;

Printf ("Destination Before Memcpy:% S / N", DEST);

PTR = Memcpy (DEST, SRC, STRLEN (SRC));

IF (PTR)

Printf ("Destination After Memcpy:% S / N", DEST);

Else

Printf ("Memcpy Failed / N");

Return 0;

}

Function Name: MemicMP Features: Compare the first n bytes of both strings S1 and S2, ignore the case: int MemicMP (Void * S1, Void * S2, Unsigned N);

#include

#include

INT main (void) {char * buf1 = "abcde123"; char * buf2 = "abcde456"; int stat; stat = memory (buf1, buf2, 5); Printf ("the strings to position 5 is"); if ("IF Stat) Printf ("not"); Printf ("THE SAME / N"); return 0;}

Function Name: Memmove Features: Mobile One byte Usage: Void * Memmove (Void * Destin, Void * Source, Unsigned N);: #include

#include

INT main (void) {char * dest = "AbcdefghijklmnopqrStuvwxyz0123456789"; char * src = "***************************" PRINTF ("Destination Prior to Memmove:% S / N", DEST); Memmove (DEST, SRC, 26); Printf ("Destination After Memmove:% S / N", DEST); RETURN 0;}

Function Name: MEMSET Features: Set all bytes in the S to the CH, the size of the S array is given by n gived: void * MEMSET (Void * S, CHAR CH, UNSIGNED N);

#include

#include

#include

INT main (void) {char buffer [] = "Hello World / N";

Printf ("Buffer Before Memset:% S / N", Buffer; MEMSET (Buffer, '*', Strlen (Buffer) - 1); Printf ("Buffer After Memset:% S / N", BUFFER; RETURN 0 }

Function name: MKDIR function: establish a directory usage: int mkdir (char * pathname);

#include

#include

#include

#include

INT main (void) {int stat;

CLRSCR (); status = mkdir ("ASDFJKLM"); (! status)? ("Directory Created / N"): (Printf ("Unable to create Directory / N));

GetCh (); system ("dir"); getch ();

Status = RMDIR ("ASDFJKLM"); (! status)? ("Directory deleted / N"): ("Unable to delete Directory);

Return 0;}

Function Name: MKTEMP Function: Establish a unique file name usage: char * mktemp (char * template);

#include

#include

INT main (void) {/ * fname defines the template for the temporary file. * /

Char * fname = "txxxxxx", * PTR;

PTR = mktemp (fname); Printf ("% s / n", ptr); return 0;}

Function Name: MK_FP Function: Set a remote pointer: Void Far * mk_fp (unsigned seg, unsigned off); example:

#include

#include

INT main (void) {INT GD, GM, I; Unsigned Int Far * screen

DetectGraph (& gd, & gm); if (gd == Hercmono) Screen = mk_fp (0xB000, 0); Else Screen = MK_FP (0xB800, 0); for (i = 0; i <26; i ) screen [i] = 0x0700 ('a' i); Return 0;} function name: MODF function: divide the number into an index and mandate usage: Double MODF (Double Value, Double * iptr);

#include

#include

INT main (void) {Double Fraction, Integer; Double Number = 100000.567;

FRAction = Modf (Number, & Integer); Printf ("The Whole and Fractional Parts OF% LF Are% LF AND% LF / N", Number, Integer, FRAction; RETURN 0;}

Function Name: MoveData Features: Copy bytes: Void MoveData (int SEGSRC, int offsrc, int segdest, int offst, unsigned numbytes);

#include

#define mono_base 0xB000

/ * SAVES THE CONTENTS OF THE MONOCHROME Screen In Buffer * / Void Save_Mono_Screen (Char Near * Buffer) {MoveData (Mono_Base, 0, _DS, (Unsigned) Buffer, 80 * 25 * 2);}

INT main (void) {charf [80 * 25 * 2]; save_mono_screen (buf);

Function Name: MoveRel function: Move the current location (CP) to a relative distance usage: Void Far MoveRel (Int DX, INT DY);

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, erroorcode; char msg [80];

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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. * / 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 cp * / moverel (100, 100);

/ * Plot a Pixel at the c. * / putpixel (getX (), gety (), getmaxcolor ());

/ * CREATE AND OUTPUT A Message At C.P. * / Sprintf (MSG, "(% D,% D)", getX (), getY ()); OutText (MSG);

/ * CLOAN UP * / GETCH (); closegraph (); return 0;}

Function Name: MoveText function: copy the screen text from a rectangular area to another: int MoveText (int LEFT, INT TOP, INT Right, Int Bottom, int newleft, int newtop); program case: #include

#include

INT main (void) {char * str = "this is a test string";

CLRSCR (); CPUTS (STR); getCh ();

MoveText (1, 1, Strlen (STR), 2, 10, 10); getCH ();

Return 0;}

Function Name: MoveTo Features: Move CP to (X, Y) Usage: Void Far Moveto (INT X, INT Y);

#include

#include

#include

#include

INT main (void) {/ * request auto detection * / int gDriver = detect, gmode, erroorcode; char msg [80];

/ * Initialize Graphics and local variables * / initgraph (& gdriver, & gmode, "");

/ * read results = graphresult (); if (error (error) / * an error opcurred * / {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. * / 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. * / putpixel (getX (), gety (), getmaxcolor ());

/ * CREATE AND OUTPUT A Message AT CP * / Sprintf (MSG, "(% D,% D)", getX (), getY ()); OutText (msg); / * Clean Up * / getch (); Closegraph (); returnograph;}

Function Name: MoveMem Function: Mobile One byte Usage: Void MoveMem (Void * Source, Void * Destin, Unsigned LEN);

#include

#include

#include

#include

INT main (void) {char * source = "borland international"; char * destination; int brightth;

Length = strlen (Source); Destination = Malloc (Length 1); MOVMEM (Source, Destination, Length); Printf ("% S / N", Destination;

Return 0;}

Function Name: NormVideo function: Select Normal Brightness Character Usage: Void NormVideo (Void);

#include

INT main (void) {normvideo (); CPrintf ("Normal Intensity Text / R / N"); Return 0;}

Function Name: NOSOSOSOD Function: Turn off PC Speaker Usage: Void Nosound (Void);

/ * Emits a 7-Hz Tone for 10 seconds.

True story: 7 Hz is the resonant frequency of a chicken's skull cavity This was determined empirically in Australia, where a new factory generating 7-Hz tones was located too close to a chicken ranch:. When the factory started up, all the chickens died .

Your PC May Not Be Able To Emit A 7-Hz Tone. * /

Int main (void) {Sound (7); delay (10000); noid ();}

Function Name: Labs Usage: Long Labs (Long N); Project: #include

#include

Int main (void) {long result; long; result = labs (x); Printf ("Number:% LD ABS Value:% LD / N", X, Result); Return 0;} Function Name: LDEXP function: Calculate the power of value * 2: Double LDEXP (Double Value, Int Exp); Procedure: #include

#include

INT main (void) {double value; double x = 2; / * ldexp raise 2 by a power of 3 dam, = ldExp (x, 3); printf ("the ldexp value is:% LF / N ", value); RETURN 0;} function name: LDIV function: two long integer numbers, return business and remainder: LDIV_T LDIV (long lnumer, long ldenom); program: / * LDIV EXAMPLE * / # incrude # include

INT main (void) {LDIV_T LX; LX = LDIV (100000L, 30000L); Printf ("100000 Div 30000 =% LD Remainder% LD / N", Lx.quot, Lx.Rem); Return 0;} function name: LFIND Function: Perform linear search usage: void * Lfind (void * key, void * base, int * nlem, int width, int (* fcmp) ()); program case: #include

#include

INT COMPARE (INT * X, INT * Y) {RETURN (* x - * y);} int main (void) {int Array [5] = {35, 87, 46, 99, 12}; size_t Nlem = 5 INT key; int * result; key = 99; result = lfind (& key, array, & nlem, sizeof (int), (int) (int)) Compare); if (Result) Printf ("Number% D Found / N", Key); Else Printf ("Number% D Not Found / N", Key); Return 0;} Function Name: LINE Function: During the designated two-point painting, Line usage: Void FAR LINE (int X0, int y0, int x1, int y1); program case: #include

#include

#include

#include

int main (void) {/ * request auto detection * / int gdriver = DETECT, gmode, errorcode; int xmax, ymax; / * initialize graphics and local variables * / initgraph (& gdriver, & gmode, ""); / * read result OF INITIALIZATION * / ERRORCODE = graphresult (); / * an error er c c = {printf ("graphics error:% s / n", grapherrormsg (errorcode)); Printf ("Press Any Key To HALT: "); getCh (); exit (1);} setColor (GetMaxColor ()); xmax = getmaxx (); ymax = getMaxy (); / * draw a diagonal line * / line (0, 0, xmax, YMAX); / * clean up * / getch (); closegraph (); return 0;} function name: LineRel function: Point painted from the current location (CP) to with CP with a given distance of a differential distance: void far LineRel (int DX, int DY);

#include

#include

int main (void) {/ * request auto detection * / int gdriver = DETECT, gmode, errorcode; char msg [80]; / * initialize graphics and local variables * / initgraph (& gdriver, & gmode, ""); / * read Result of initialization * / errorcode = graphresult (); if (ErrorCode! = GROK) {Printf ("Graphics Error:% S / N", GrapherrorMSG (ErrorCode)); Printf ("Press Any Key to Halt:"); getch (); exit (1);} / * Move the cp to location (20, 30) * / Moveto (20, 30); / * Create and Output a Message At (20, 30) * / Sprintf (MSG, " (% D,% d) ", getX (), get ()); Outtextxy (20, 30, msg); / * Draw a line to a point a relative distance away from the current value of cp * / linerel (100 , 100); / * CREATE AND OUTPUT A Message AT CP * / Sprintf (MSG, "(% D,% D)", getX (), getY ()); OutText (msg); / * Clean Up * / getch (); Return 0;} function name: localtime function: Transition date and time to structural usage: struct tm * localtime (long * clock); program: #include

#include

#include

INT main (void) {Time_t Timer; StructTM * TBLOCK; / * GETS TIME OF DAY * / TIMER = TIME (NULL); / * Converts Date / Time to a structure * / tblock = localtime (& Timer); Printf (" Local Time IS:% S, ASCTIME (TBLOCK)); Return 0;} function name: LOCK function: Settings file shared lock usage: int Lock (INT HANDLE, long offset, long length); program: # includ # include

#include

#include

#include

#include

INT main (void) {Int Handle, Status; Long length; / * Must Have Dos Share.exe Loaded for * / / * file locking to function protection * / handle = Sopen ("c: //autoexec.bat", o_rdonly , SH_DENYNO, S_IREAD; if (Handle <0) {Printf ("Sopen FaileD / N"); exit (1);} length = filelength; status = lock (Handle, 0L, Length / 2); if (status == 0) Printf ("Lock successEDED / 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;} function name: log function: logarithm LN (X) Usage: double log (double x); program Example: #include

#include

INT main (void) {double result; results = log (x); Printf ("THE NATURAL LO% LF IS% LF / N", X, Result); return 0;} function name: log10 Function: Logo Log Usage: Double Log10 (Double X); Procedure: #include

#include

INT main (void) {Double Result; double x = 800.6872; result = log10 (x); Printf ("THE COMMON LO% LF IS% LF / N", X, Result); Return 0;} function name: longjump Function: Perform non-local transfer usage: void longjump (JMP_BUF ENV, INT VAL); program: #include

#include

#include

Void subroutine; int main (void) {int value; jmp_buf jumper; value = setjmp (jumper); if (value! = 0) {Printf ("longjmp with value% d / n", value); exit Value);} Printf ("About to Call Subroutine ... / N); Subroutine (Jumper); Return 0;} Void Subroutine {longjmp (Jumper, 1);} function name: lowvideo function: Select Low brightness character usage: void lowvideo (void); program case: #includeint main (void) {clrs (); highvideo (); cprintf ("high intesis Text / r / n"); lowvideo (); gotoxy (1, 2); CPRINTF ("LOW INTENSITY TEXT / R / N"); return 0;} function name: lrotl, _lrotl function: unsigned long-intensive number left loop displacement usage: unsigned long Lvalue, INT count); unsigned long _lrotl (unsigned long Lvalue, int count); program example: / * lrotl example * / #include

#include

INT main (void) {unsigned long value = 100; result = _lrotl (value, 1); Printf ("The value% lu rotated left one bit is:% lu / n", value, result); return; Return 0;} function name: LSearch function: linear search usage: void * LSearch (const void * key, void * base, size_t * nlem, size_t width, int (* fcmp) (const void *, const void *); program Example: #include

#include

INT COMPARE (INT * X, INT * Y) {RETURN (* x - * y);} int main (void) {int Array [5] = {35, 87, 46, 99, 12}; size_t Nlem = 5 INT key; int * result; key = 99; result = lfind (& key, array, & nlem, sizeof (int), (int) (int)) Compare); if (Result) Printf ("Number% D Found / N", Key); Else Printf ("Number% D Not Found / N", Key); Return 0;} Function Name: LSeek Function: Mobile File Read / Write Pointer Law: Long Lseek INT HANDLE, long offset, int.comwhere; program: #include

#include

#include

#include

#include

转载请注明原文地址:https://www.9cbs.com/read-114721.html

New Post(0)