HEADER FILES
INCLUDE SYNTAX
Both user and system header files are included using the preprocessing
directive `#include'. It has two variants:
#INCLUDE
This variant is used for system header files. It searches for a file named
file in a standard list of system directories. You can prepend directories to
this list with the -I option (see Invocation).
#INCLUDE "FILE"
This variant is used for header files of your own program. It searches for a
file named file first in the directory containing the current file, then in
the quote directories and then the same directories used for
You can prepend directories to the list of quote directories with the -iquote
option.
The argument of `#include', whether delimited with quote marks or angle
brackets, behaves like a string constant in that comments are not recognized,
and macro names are not expanded.
Thus, #include
However, if backslashes occur within file, they are considered ordinary text
characters, not escape characters. None of the character escape sequences
appropriate to string constants in C are processed.
Thus, #include "x\n\\y" specifies a filename containing three backslashes.
(Some systems interpret `\' as a pathname separator.
All of these also interpret `/' the same way. It is most portable to use only
`/'.)
It is an error if there is anything (other than comments) on the line after
the file name.
STDIO.H—(STANDARD BUFFERED INPUT/OUTPUT)
SYNTAX
#INCLUDE
DESCRIPTON
The
constant expressions:
FILENAME_MAX Maximum size in bytes of the longest filename string that the
implementation guarantees can be opened.
FOPEN_MAX Number of streams which the implementation guarantees can be
open simultaneously. The value will be at
l least eight.
_IOFBF Input/output fully buffered.
_IOLBF Input/output line buffered.
_IONBF Input/output unbuffered.
L_ctermid Maximum size of character array to hold ctermid() output.
L_cuserid Maximum size of character array to hold cuserid()
output. (LEGACY)
L_tmpnam. Maximum size of character array to hold tmpnam() output.
SEEK_CUR . Seek relative to current position.
SEEK_END Seek relative to end-of-file.
SEEK_SET Seek relative to start-of-file.
TMP_MAX Minimum number of unique filenames generated by tmpnam().
Maximum number of times an application
c can call tmpnam() reliably. The value of TMP_MAX
will be at least 10,000.
The following macro name is defined as a negative integral constant
expression:
The following macro name is defined as a null pointer constant:
NULL (Null pointer).
The following macro name is defined as a string constant:
P_tmpdir default directory prefix for tempnam().
The following macro names are defined as expressions of type pointer to FILE:
stderr Standard error output stream.
stdin Standard input stream.
Stdout Standard output stream.
The following data types are defined through typedef:
fpos_t Type containing all information needed to specify uniquely
every position within a file.
va_list As described in
size_t As described in
Function prototypes must be provided for use with an ISO C compiler.
CHAR *CTERMID(CHAR *);
CHAR *CUSERID(CHAR *);(LEGACY)
INT FCLOSE(FILE *);
FILE *FDOPEN(INT, CONST CHAR *);
INT FEOF(FILE *);
INT FERROR(FILE *);
INT FFLUSH(FILE *);
INT FGETC(FILE *);
INT FGETPOS(FILE *, FPOS_T *);
CHAR *FGETS(CHAR *, INT, FILE *);
INT FILENO(FILE *);
VOID FLOCKFILE(FILE *);
FILE *FOPEN(CONST CHAR *, CONST CHAR *);
INT FPRINTF(FILE *, CONST CHAR *, ...);
INT FPUTC(INT, FILE *);
INT FPUTS(CONST CHAR *, FILE *);
SIZE_T FREAD(VOID *, SIZE_T, SIZE_T, FILE *);
FILE *FREOPEN(CONST CHAR *, CONST CHAR *, FILE *);
INT FSCANF(FILE *, CONST CHAR *, ...);
INT FSEEK(FILE *, LONG INT, INT);
INT FSEEKO(FILE *, OFF_T, INT);
INT FSETPOS(FILE *, CONST FPOS_T *);
LONG INT FTELL(FILE *);
OFF_T FTELLO(FILE *);
INT FTRYLOCKFILE(FILE *);
VOID FUNLOCKFILE(FILE *);
SIZE_T FWRITE(CONST VOID *, SIZE_T, SIZE_T, FILE *);
INT GETC(FILE *);
INT GETCHAR(VOID);
INT GETC_UNLOCKED(FILE *);
INT GETCHAR_UNLOCKED(VOID);
INT GETOPT(INT, CHAR * CONST[], CONST CHAR); (LEGACY)
CHAR *GETS(CHAR *);
INT GETW(FILE *);
INT PCLOSE(FILE *);
VOID PERROR(CONST CHAR *);
FILE *POPEN(CONST CHAR *, CONST CHAR *);
INT PRINTF(CONST CHAR *, ...);
INT PUTC(INT, FILE *);
INT PUTCHAR(INT);
INT PUTC_UNLOCKED(INT, FILE *);
INT PUTCHAR_UNLOCKED(INT);
INT PUTS(CONST CHAR *);
INT PUTW(INT, FILE *);
INT REMOVE(CONST CHAR *);
INT RENAME(CONST CHAR *, CONST CHAR *);
VOID REWIND(FILE *);
INT SCANF(CONST CHAR *, ...);
VOID SETBUF(FILE *, CHAR *);
INT SETVBUF(FILE *, CHAR *, INT, SIZE_T);
INT SNPRINTF(CHAR *, SIZE_T, CONST CHAR *, ...);
INT SPRINTF(CHAR *, CONST CHAR *, ...);
INT SSCANF(CONST CHAR *, CONST CHAR *, INT ...);
CHAR *TEMPNAM(CONST CHAR *, CONST CHAR *);
FILE *TMPFILE(VOID);
CHAR *TMPNAM(CHAR *);
INT UNGETC(INT, FILE *);
INT VFPRINTF(FILE *, CONST CHAR *, VA_LIST);
INT VPRINTF(CONST CHAR *, VA_LIST);
INT VSNPRINTF(CHAR *, SIZE_T, CONST CHAR *, VA_LIST);
INT VSPRINTF(CHAR *, CONST CHAR *, VA_LIST);
CONIO.H
conio.h header contains functions for console input/output. Some of the most
commonly used functions of conio.h are clrscr, getch, getche, kbhit etc.
Functions of conio.h can be used to clear screen, change color of text and
background, move text, check if a key is pressed or not and many more.
conio.h file is provided by borland turbo c compiler and gcc compiler doesn't
support it.
GETCH
GETCHE
GOTOXY
KBHIT
WHEREX
WHEREY
TEXTCOLOR
TEXTBACKGROUND
Mathematics is relatively straightforward library to use again. You must
#include
compilation:
CC MATHPROG.C -O MATHPROG -LM
A common source of error is in forgetting to include the
yes experienced programmers make this error also). Unfortunately the C
compiler does not help much. Consider:
DOUBLE X;
X = SQRT(63.9);
Having not seen the prototype for sqrt the compiler (by default) assumes that
the function returns an int and converts the value to a double with
meaningless results.
above they should be easy to use and we have already used some in previous
examples. We give no further examples here:
DOUBLE ASIN(DOUBLE X) -- COMPUTE ARC SINE OF X.
DOUBLE ATAN(DOUBLE X) -- COMPUTE ARC TANGENT OF X.
DOUBLE ATAN2(DOUBLE Y, DOUBLE X) -- COMPUTE ARC TANGENT OF Y/X, USING THE
SIGNS OF BOTH ARGUMENTS TO DETERMINE THE QUADRANT OF THE RETURN VALUE.
DOUBLE CEIL(DOUBLE X) -- GET SMALLEST INTEGRAL VALUE THAT EXCEEDS X.
DOUBLE COS(DOUBLE X) -- COMPUTE COSINE OF ANGLE IN RADIANS.
DOUBLE COSH(DOUBLE X) -- COMPUTE THE HYPERBOLIC COSINE OF X.
DIV_T DIV(INT NUMBER, INT DENOM) -- DIVIDE ONE INTEGER BY ANOTHER.
DOUBLE EXP(DOUBLE X -- COMPUTE EXPONENTIAL OF X
DOUBLE FABS (DOUBLE X ) -- COMPUTE ABSOLUTE VALUE OF X.
DOUBLE FLOOR(DOUBLE X) -- GET LARGEST INTEGRAL VALUE LESS THAN X.
DOUBLE FMOD(DOUBLE X, DOUBLE Y) -- DIVIDE X BY Y WITH INTEGRAL QUOTIENT AND
RETURN REMAINDER.
DOUBLE FREXP(DOUBLE X, INT *EXPPTR) -- BREAKS DOWN X INTO MANTISSA AND
EXPONENT OF NO.
LABS(LONG N) -- FIND ABSOLUTE VALUE OF LONG INTEGER N.
DOUBLE LDEXP(DOUBLE X, INT EXP) -- RECONSTRUCTS X OUT OF MANTISSA AND EXPONENT
OF TWO.
LDIV_T LDIV(LONG NUMBER, LONG DENOM) -- DIVIDE ONE LONG INTEGER BY ANOTHER.
DOUBLE LOG(DOUBLE X) -- COMPUTE LOG(X).
DOUBLE LOG10 (DOUBLE X ) -- COMPUTE LOG TO THE BASE 10 OF X.
DOUBLE MODF(DOUBLE X, DOUBLE *INTPTR) -- BREAKS X INTO FRACTIONAL AND INTEGER
PARTS.
DOUBLE POW (DOUBLE X, DOUBLE Y) -- COMPUTE X RAISED TO THE POWER Y.
DOUBLE SIN(DOUBLE X) -- COMPUTE SINE OF ANGLE IN RADIANS.
DOUBLE SINH(DOUBLE X) - COMPUTE THE HYPERBOLIC SINE OF X.
DOUBLE SQRT(DOUBLE X) -- COMPUTE THE SQUARE ROOT OF X.
VOID SRAND(UNSIGNED SEED) -- SET A NEW SEED FOR THE RANDOM NUMBER GENERATOR
(RAND).
DOUBLE TAN(DOUBLE X) -- COMPUTE TANGENT OF ANGLE IN RADIANS.
DOUBLE TANH(DOUBLE X) -- COMPUTE THE HYPERBOLIC TANGENT OF X.
MATH CONSTANTS
The math.h library defines many (often neglected) constants. It is always
advisable to use these definitions:
HUGE -- THE MAXIMUM VALUE OF A SINGLE-PRECISION FLOATING-POINT NUMBER.
M_E -- THE BASE OF NATURAL LOGARITHMS (E).
M_LOG2E -- THE BASE-2 LOGARITHM OF E.
M_LOG10E - THE BASE-10 LOGARITHM OF E.
M_LN2 -- THE NATURAL LOGARITHM OF 2.
M_LN10 -- THE NATURAL LOGARITHM OF 10.
M_PI -- ?.
M_PI_2 -- ?/2.
M_PI_4 -- ?/4.
M_1_PI -- 1/?.
M_2_PI -- 2/?.
M_2_SQRTPI -- 2/?.
M_SQRT2 -- THE POSITIVE SQUARE ROOT OF 2.
M_SQRT1_2 -- THE POSITIVE SQUARE ROOT OF 1/2.
MAXFLOAT -- THE MAXIMUM VALUE OF A NON-INFINITE SINGLE- PRECISION FLOATING
POINT NUMBER.
HUGE_VAL -- POSITIVE INFINITY.
There are also a number a machine dependent values defined in #include
WRAPPER HEADERS
Sometimes it is necessary to adjust the contents of a system-provided header
file without editing it directly.
GCC's fixincludes operation does this, for example.
One way to do that would be to create a new header file with the same name and
insert it in the search path before the original header.
That works fine as long as you're willing to replace the old header entirely.
But what if you want to refer to the old header from the new one?
You cannot simply include the old header with `#include'.
That will start from the beginning, and find your new header again.
If your header is not protected from multiple inclusion (see Once-Only
Headers), it will recurse infinitely and cause a fatal error.
You could include the old header with an absolute pathname:
#INCLUDE "/USR/INCLUDE/OLD-HEADER.H"
This works, but is not clean; should the system headers ever move, you would
have to edit the new headers to match.
There is no way to solve this problem within the C standard, but you can use
the GNU extension `#include_next'.
It means, “Include the next file with this name”. This directive works like
`#include' except in searching for the specified file: it starts searching the
list of header file directories after the directory in which the current file
was found.
Suppose you specify -I /usr/local/include, and the list of directories to
search also includes /usr/include; and suppose both directories contain
signal.h.
Ordinary #include
If that file contains #include_next
directory, and finds the file in /usr/include.
`#include_next' does not distinguish between
does it check that the file you specify has the same name as the current file.
It simply looks for the file named, starting with the directory in the search
path after the one where the current file was found.
The use of `#include_next' can lead to great confusion. We recommend it be
used only when there is no other alternative. In particular, it should not be
used in the headers belonging to a specific program; it should be used only to
make global corrections along the lines of fixincludes.
A string in C is a sequence of zero or more characters followed by a NULL ()
character:
It is important to preserve the NULL terminating character as it is how C
defines and manages variable length strings.
All the C standard library functions require this for successful operation.
In general, apart from some length-restricted functions ( strncat(), strncmp,
() and strncpy()), unless you create strings by hand you should not encounter
any such problems, . You should use the many useful string handling functions
and not really need to get your hands dirty dismantling and assembling
strings.
BASIC STRING HANDLING FUNCTIONS
All the string handling functions are prototyped in:
#INCLUDE
The common functions are described below:
CHAR *STPCPY (CONST CHAR *DEST,CONST CHAR *SRC) -- COPY ONE STRING INTO
ANOTHER.
INT STRCMP(CONST CHAR *STRING1,CONST CHAR *STRING2) - COMPARE STRING1 AND
STRING2 TO DETERMINE ALPHABETIC ORDER.
CHAR *STRCPY(CONST CHAR *STRING1,CONST CHAR *STRING2) -- COPY STRING2 TO
STRINGL.
CHAR *STRERROR(INT ERRNUM) -- GET ERROR MESSAGE CORRESPONDING TO SPECIFIED
ERROR NUMBER.
INT STRLEN(CONST CHAR *STRING) -- DETERMINE THE LENGTH OF A STRING.
CHAR *STRNCAT(CONST CHAR *STRING1, CHAR *STRING2, SIZE_T N) -- APPEND N
CHARACTERS FROM STRING2 TO STRINGL.
INT STRNCMP(CONST CHAR *STRING1, CHAR *STRING2, SIZE_T N) -- COMPARE FIRST N
CHARACTERS OF TWO STRINGS.
CHAR *STRNCPY(CONST CHAR *STRING1,CONST CHAR *STRING2, SIZE_T N) -- COPY FIRST
N CHARACTERS OF STRING2 TO STRINGL .
INT STRCASECMP(CONST CHAR *S1, CONST CHAR *S2) -- CASE INSENSITIVE VERSION OF
STRCMP().
INT STRNCASECMP(CONST CHAR *S1, CONST CHAR *S2, INT N) -- CASE INSENSITIVE
VERSION OF STRNCMP().
The use of most of the functions is straightforward, for example:
CHAR *STR1 = "HELLO";
CHAR *STR2;
INT LENGTH;
LENGTH = STRLEN("HELLO"); /* LENGTH = 5 */
(VOID) STRCPY(STR2,STR1);
Note
That both strcat() and strcopy() both return a copy of their first argument
which is the destination array. Note the order of the arguments is destination
array followed by source array which is sometimes easy to get the wrong around
when programming.
The strcmp() function lexically compares the two input strings and returns:
LESS THAN ZERO
-- IF STRING1 IS LEXICALLY LESS THAN STRING2
ZERO
-- IF STRING1 AND STRING2 ARE LEXICALLY EQUAL
GREATER THAN ZERO
-- IF STRING1 IS LEXICALLY GREATER THAN STRING2
THIS CAN ALSO CONFUSE BEGINNERS AND EXPERIENCE PROGRAMMERS FORGET THIS TOO.
The strncat(), strncmp,() and strncpy() copy functions are string restricted
version of their more general counterparts. They perform a similar task but
only up to the first n characters. Note the the NULL terminated requirement
may get violated when using these functions, for example:
CHAR *STR1 = "HELLO";
CHAR *STR2;
INT LENGTH = 2;
(VOID) STRCPY(STR2,STR1, LENGTH); /* STR2 = "HE" */
str2 is NOT NULL TERMINATED!! -- BEWARE
STRING SEARCHING
The library also provides several string searching functions:
CHAR *STRCHR(CONST CHAR *STRING, INT C) -- FIND FIRST OCCURRENCE OF
CHARACTER C IN STRING.
CHAR *STRRCHR(CONST CHAR *STRING, INT C) -- FIND LAST OCCURRENCE OF CHARACTER
C IN STRING.
CHAR *STRSTR(CONST CHAR *S1, CONST CHAR *S2) -- LOCATES THE FIRST OCCURRENCE
OF THE STRING S2 IN STRING S1.
CHAR *STRPBRK(CONST CHAR *S1, CONST CHAR *S2) -- RETURNS A POINTER TO THE
FIRST OCCURRENCE IN STRING S1 OF ANY CHARACTER FROM STRING S2, OR A NULL
POINTER IF NO CHARACTER FROM S2 EXISTS IN S1
SIZE_T STRSPN(CONST CHAR *S1, CONST CHAR *S2) -- RETURNS THE NUMBER OF
CHARACTERS AT THE BEGINING OF S1 THAT MATCH S2.
SIZE_T STRCSPN(CONST CHAR *S1, CONST CHAR *S2) -- RETURNS THE NUMBER OF
CHARACTERS AT THE BEGINING OF S1 THAT DO NOT MATCH S2.
CHAR *STRTOK(CHAR *S1, CONST CHAR *S2) -- BREAK THE STRING POINTED TO BY S1
INTO A SEQUENCE OF TOKENS, EACH OF WHICH IS DELIMITED BY ONE OR MORE
CHARACTERS FROM THE STRING POINTED TO BY S2.
CHAR *STRTOK_R(CHAR *S1, CONST CHAR *S2, CHAR **LASTS) -- HAS THE SAME
FUNCTIONALITY AS STRTOK() EXCEPT THAT A POINTER TO A STRING PLACEHOLDER LASTS
MUST BE SUPPLIED BY THE CALLER.
strchr() and strrchr() are the simplest to use, for example:
CHAR *STR1 = "HELLO";
CHAR *ANS;
ANS = STRCHR(STR1,'L');
After this execution, ans points to the location str1 + 2
strpbrk() is a more general function that searches for the first occurrence of
any of a group of characters, for example:
CHAR *STR1 = "HELLO";
CHAR *ANS;
ANS = STRPBRK(STR1,'AEIOU');
Here, ans points to the location str1 + 1, the location of the first e.
strstr() returns a pointer to the specified search string or a null pointer if
the string is not found. If s2 points to a string with zero length (that is,
the string ""), the function returns s1. For example,
CHAR *STR1 = "HELLO";
CHAR *ANS;
ANS = STRSTR(STR1,'LO');
WILL YIELD ANS = STR + 3.
strtok() is a little more complicated in operation.
If the first argument is not NULL then the function finds the position of any
of the second argument characters.
However, the position is remembered and any subsequent calls to strtok() will
start from this position if on these subsequent calls the first argument is
NULL.
For example, If we wish to break up the string str1 at each space and print
each token on a new line we could do:
CHAR *STR1 = "HELLO BIG BOY";
CHAR *T1;
FOR ( T1 = STRTOK(STR1," ");
T1 != NULL;
T1 = STRTOK(NULL, " ") )
PRINTF("%S\N",T1);
HERE WE USE THE FOR LOOP IN A NON-STANDARD COUNTING FASHION:
THE INITIALISATION CALLS STRTOK() LOADS THE FUNCTION WITH THE STRING STR1
WE TERMINATE WHEN T1 IS NULL
WE KEEP ASSIGNING TOKENS OF STR1 TO T1 UNTIL TERMINATION BY CALLING STRTOK()
WITH A NULL FIRST ARGUMENT.
CHARACTER CONVERSIONS AND TESTING: CTYPE.H
We conclude this chapter with a related library #include
contains many useful functions to convert and test single characters. The
common functions are prototypes as follows:
CHARACTER TESTING:
INT ISASCII(INT C) -- TRUE IF C IS ASCII .
INT ISCNTRL(INT C) -- TRUE IF C IS A CONTROL CHARACTER.
INT ISDIGIT(INT C) -- TRUE IF C IS A DECIMAL DIGIT
INT ISGRAPH(INT C) -- TRUE IF C IS A GRAPHICAL CHARACTER.
INT ISLOWER(INT C) -- TRUE IF C IS A LOWERCASE LETTER
INT ISPRINT(INT C) -- TRUE IF C IS A PRINTABLE CHARACTER
INT ISPUNCT (INT C) -- TRUE IF C IS A PUNCTUATION CHARACTER.
INT ISSPACE(INT C) -- TRUE IF C IS A SPACE CHARACTER.
INT ISUPPER(INT C) -- TRUE IF C IS AN UPPERCASE LETTER.
INT ISXDIGIT(INT C) -- TRUE IF C IS A HEXADECIMAL DIGIT
CHARACTER CONVERSION:
INT TOASCII(INT C) -- CONVERT C TO ASCII .
TOLOWER(INT C) -- CONVERT C TO LOWERCASE.
INT TOUPPER(INT C) -- CONVERT C TO UPPERCASE.
MEMORY.H
Finally we briefly overview some basic memory operations. Although not
strictly string functions the functions are prototyped in #include
VOID *MEMCHR (VOID *S, INT C, SIZE_T N) -- SEARCH FOR A CHARACTER IN A BUFFER
.
INT MEMCMP (VOID *S1, VOID *S2, SIZE_T N) -- COMPARE TWO BUFFERS.
VOID *MEMCPY (VOID *DEST, VOID *SRC, SIZE_T N) -- COPY ONE BUFFER INTO ANOTHER
.
VOID *MEMMOVE (VOID *DEST, VOID *SRC, SIZE_T N) -- MOVE A NUMBER OF BYTES FROM
ONE BUFFER LO ANOTHER.
VOID *MEMSET (VOID *S, INT C, SIZE_T N) -- SET ALL BYTES OF A BUFFER TO A
GIVEN CHARACTER.
Their use is fairly straightforward and not dissimilar to comparable string
operations (except the exact length (n) of the operations must be specified as
there is no natural termination here).
Note
That in all case to bytes of memory are copied. The sizeof() function comes in
handy again here, for example:
CHAR SRC[SIZE],DEST[SIZE];
INT ISRC[SIZE],IDEST[SIZE];
MEMCPY(DEST,SRC, SIZE); /* COPY CHARS (BYTES) OK */
MEMCPY(IDEST,ISRC, SIZE*SIZEOF(INT)); /* COPY ARRAYS OF INTS */
memmove() behaves in exactly the same way as memcpy() except that the source
and destination locations may overlap.
memcmp() is similar to strcmp() except here unsigned bytes are compared and
returns less than zero if s1 is less than s2 etc.
STDLIB.H
Integer Functions, Random Number, String Conversion, Searching and Sorting
To use all functions in this library you must:
#INCLUDE
There are three basic categories of functions:
Arithmetic
Random Numbers
ARITHMETIC FUNCTIONS
There are 4 basic integer functions:
INT ABS(INT NUMBER);
LONG INT LABS(LONG INT NUMBER);
DIV_T DIV(INT NUMERATOR,INT DENOMINATOR);
LDIV_T LDIV(LONG INT NUMERATOR, LONG INT DENOMINATOR);
Essentially there are two functions with integer and long integer
compatibility.
ABS
functions return the absolute value of its number arguments. For example, abs
(2) returns 2 as does abs(-2).
DIV
takes two arguments, numerator and denominator and produces a quotient and a
remainder of the integer division. The div_t structure is defined (in
stdlib.h) as follows:
TYPEDEF STRUCT {
INT QUOT; /* QUOTIENT */
INT REM; /* REMAINDER */
} DIV_T;
(ldiv_t is similarly defined).
Thus:
#INCLUDE
....
INT NUM = 8, DEN = 3;
DIV_T ANS;
ANS = DIV(NUM,DEN);
PRINTF("ANSWER:\N\T QUOTIENT = %D\N\T REMAINDER = %D\N", \
ANS.QUOT,ANS.REM);
Produces the following output:
Answer:
QUOTIENT = 2
REMAINDER = 2
RANDOM NUMBERS
Random numbers are useful in programs that need to simulate random events,
such as games, simulations and experimentations.
In practice no functions produce truly random data -- they produce pseudo-
random numbers.
These are computed form a given formula (different generators use different
formulae) and the number sequences they produce are repeatable. A seed is
usually set from which the sequence is generated. Therefore is you set the
same seed all the time the same set will be be computed.
One common technique to introduce further randomness into a random number
generator is to use the time of the day to set the seed, as this will always
be changing.
There are many (pseudo) random number functions in the standard library. They
all operate on the same basic idea but generate different number sequences
(based on different generator functions) over different number ranges.
The simplest set of functions is:
INT RAND(VOID);
VOID SRAND(UNSIGNED INT SEED);
rand() returns successive pseudo-random numbers in the range from 0 to
(2^15)-1.
srand() is used to set the seed. A simple example of using the time of the day
to initiate a seed is via the call:
SRAND() (UNSIGNED INT) TIME( NULL ));
The following program card.c illustrates the use of these functions to
simulate a pack of cards being shuffled:
/*
** USE RANDOM NUMBERS TO SHUFFLE THE "CARDS" IN THE DECK. THE SECOND
** ARGUMENT INDICATES THE NUMBER OF CARDS. THE FIRST TIME THIS
** FUNCTION IS CALLED, SRAND IS CALLED TO INITIALIZE THE RANDOM
** NUMBER GENERATOR.
*/
#INCLUDE
#INCLUDE
#DEFINE TRUE 1
#DEFINE FALSE 0
VOID SHUFFLE( INT *DECK, INT N_CARDS )
{
INT I;
STATIC INT FIRST_TIME = TRUE;
/*
** SEED THE RANDOM NUMBER GENERATOR WITH THE CURRENT TIME
** OF DAY IF WE HAVEN'T DONE SO YET.
*/
IF( FIRST_TIME ){
FIRST_TIME = FALSE;
SRAND( (UNSIGNED INT)TIME( NULL ) );
}
/*
** "SHUFFLE" BY INTERCHANGING RANDOM PAIRS OF CARDS.
*/
FOR( I = N_CARDS - 1; I > 0; I -= 1 ){
INT WHERE;
INT TEMP;
WHERE = RAND() % I;
TEMP = DECK[ WHERE ];
DECK[ WHERE ] = DECK[ I ];
DECK[ I ] = TEMP;
}
}
There are several other random number generators available in the standard
library:
DOUBLE ERAND48(UNSIGNED SHORT XSUBI[3]);
LONG LRAND48(VOID);
LONG NRAND48(UNSIGNED SHORT XSUBI[3]);
LONG MRAND48(VOID);
LONG JRAND48(UNSIGNED SHORT XSUBI[3]);
VOID SRAND48(LONG SEED);
UNSIGNED SHORT *SEED48(UNSIGNED SHORT SEED[3]);
VOID LCONG48(UNSIGNED SHORT PARAM[7]);
This family of functions generates uniformly distributed pseudo-random
numbers.
precision floating-point values uniformly distributed over the interval [0.0,
1.0).
Functions lrand48() and nrand48() return non-negative long integers uniformly
distributed over the interval [0, 2**31).
Functions mrand48() and jrand48() return signed long integers uniformly
distributed over the interval [-2**31, 2**31).
Functions srand48(), seed48(), and lcong48() set the seeds for drand48(),
lrand48(), or mrand48() and one of these should be called first.
STRING CONVERSION
There are a few functions that exist to convert strings to integer, long
integer and float values. They are:
DOUBLE ATOF(CHAR *STRING) -- CONVERT STRING TO FLOATING POINT VALUE.
INT ATOI(CHAR *STRING) -- CONVERT STRING TO AN INTEGER VALUE
INT ATOL(CHAR *STRING) -- CONVERT STRING TO A LONG INTEGER VALUE.
DOUBLE STRTOD(CHAR *STRING, CHAR *ENDPTR) -- CONVERT STRING TO A FLOATING
POINT VALUE.
LONG STRTOL(CHAR *STRING, CHAR *ENDPTR, INT RADIX) -- CONVERT STRING TO A LONG
INTEGER USING A GIVEN RADIX.
UNSIGNED LONG STRTOUL(CHAR *STRING, CHAR *ENDPTR, INT RADIX) -- CONVERT STRING
TO UNSIGNED LONG.
Most of these are fairly straightforward to use.
For example:
CHAR *STR1 = "100";
CHAR *STR2 = "55.444";
CHAR *STR3 = " 1234";
CHAR *STR4 = "123FOUR";
CHAR *STR5 = "INVALID123";
INT I;
FLOAT F;
I = ATOI(STR1); /* I = 100 */
F = ATOF(STR2); /* F = 55.44 */
I = ATOI(STR3); /* I = 1234 */
I = ATOI(STR4); /* I = 123 */
I = ATOI(STR5); /* I = 0 */
NOTE:
LEADING BLANK CHARACTERS ARE SKIPPED.
TRAILING ILLEGAL CHARACTERS ARE IGNORED.
IF CONVERSION CANNOT BE MADE ZERO IS RETURNED AND ERRNO IS SET WITH THE VALUE
ERANGE.
DOS.H
dos.h in c: dos.h header file of c language contains functions for handling
interrupts, producing sound, date and time functions etc. It is borland
specific and works in turbo c compiler.
GETDATE
GETTIME
NOSOUND
SETDATE
SLEEP
SOUND
No comments:
Post a Comment