Professional Documents
Culture Documents
Language of UNIX operating system
FORTRAN, 1957, John Backus
ALGOL58/60, Friedrich L Bauer
CPL, Combined Programming Language, Christopher Strachey Cambridge/London 1963
BCPL, Basic CPL, Martin Richards, 1967, Cambridge
B, Ken Thompson, 1970 (on PDP7)
C, Dennis M Ritchie, 1972 (on DECPDP11)
ANSI C Committee set up in 1983, published 1989, ISO C90
Amendment 1 1995
C99, C11 (including eg multithreading)
Objective C, Apple OS, Brad Cox, 1981, OO
superset of C
originally called "C with Classes", 1979
Dr Bjarne J Stroustrup, 1983
ANSI C++ Committee 19891998
"The C++ Programming Language", 1986, 1991, 1997, (SE 00), 2013 AddisonWesley
"The Annotated C++ Reference Manual", + Margaret A Ellis, 1990, AddisonWesley
ANSI C++ 19891998 (corrections 2003)
2005, C++11, ?C++14 (including eg multithreading) and C++17
Java, Sun Microsystems 1995, James Gosling
C#, Microsoft, Anders Hejlsberg, 1999, easier but less powerful than C++
D, Zortech, Walter Bright, 2001, easier than C++ and as powerful
"The C Programming Language", + Brian W Kernighan, 1978, 1988, PrenticeHall
Lowlevel, easier to read than using machine code or assembly language
30 reserved words c/w over 400 in COBOL
Portable, eg source code for PC should recompile on Mac, Sun, VAX, etc
/* hello.c: displays "hello" on screen */
#include <stdio.h>
main()
{
printf("Hello!\n");
}
Put comments in between /* and */
Comments can appear in middle of code and/or extend over more than 1 line
Should use comment(s) at start of each source file to describe purpose, etc
Should also use comments where code is difficult to understand or not portable
# preprocessor directives tell compiler about the program
includes function(s) from C library's STandarD Input/Output Header file
execution begins at the function called main()
put function's argument(s) between ( and )
() means any number/type of arguments supplied by caller
The operating system calls main()
Put function's statements between { and }
printf() is <stdio.h>'s formatted output function
Put character string between " and "
Escape sequence \n in character string prints a newline (= 1 character)
Put; at the end of each statement
/* sum.c: displays sum of 2 numbers input by the user */
#include <stdio.h>
main()
{
float first, second, sum;
printf("enter 1st number: ");
scanf("%f", &first);
printf("enter 2nd number: ");
scanf("%f", &second);
sum = first + second;
printf("%f + %f = %f\n", first, second, sum);
}
Declare variables just below left brace {
Float declares variables first, second and total as floating point (real)
numbers
Could use int for integer, double for double precision floating point or char
For a single character
scanf() is <stdio.h>'s formatted input function
conversion character %f accepts number as a float
Use %d for an int, %c for a char and %s for a character string
%f etc can also be used by printf() to display values of variables
The string is first printf()/scanf() argument, then variables used in %f etc
Use & before variable name in scanf() but not in printf()
Variables can be initialised (at time of declaration), eg
int i = 1;
The If Statement
if (x == 1) {
printf("x is one\n");
printf("Goodbye"\n");
} else if (x == 2)
printf("x is two\n");
else
printf("x is neither one nor two\n");
Condition in parentheses to override precedence
else part is optional
Use == to test if x is 1, = would set x to 1
Use ! for not, && for and, || for or
Can use { and } for compound statements (= one or more simple statements)
else paired with nearest preceding unpaired if, use { and } to change order
'a' is ASCII number
Compiler automatically appends null character '\0' (zero) to character strings
"a" is the character string (= { 'a', '\0' })
Use ' and ' for characters in conditions, eg
if (c >= 'A' && c <= 'Z')
printf("%c is a capital letter\n", c);
Condition set to zero if false ("0 means NO"), nonzero if true, eg
if (!a && b)
printf("a is zero, b is not\n");
EOF character for end of file, eg user has pressed escape key, eg
if (c = EOF)
printf("end of file\n");
Note that
max = (a > b) ? a : b;
Produces faster machine code than
if (a > b)
max = a;
else
max = b;
Can use compound statements between ? and : and between : and;
Can declare variables just below { in any compound statement
The For Statement
int i;
for (i = 0; i < 10; i++)
printf("%d\n", i);
(initial statements; terminating condition; other statements)
Similar to PERFORM ... VARYING
if a part, eg initial, is a compound statement, use comma operator to separate
Any/all clauses can be left out (but leave semicolons in)
int i = 0;
for (; i < 10;) {
printf("%d\n", i++);
printf("Hello\n");
}
{ and } must for compound statements
x++ increments x (x = x + 1) after it is next used
y decrements y before it is next used
The While Statement
int i = 0;
while (i < 10)
printf("%d\n", i++);
Similar to PERFORM ... UNTIL
Any condition in any statement returns 0 if false or 1 if true
Any nonzero number translates as true
Condition tested before loop so statements may not be executed at all
Use { and } for compound statements
while (1) is an infinite loop, but could use
for (;;)
The Do Statement
i = 0;
do {
printf("%d\n", i++);
} while (i <= 10);
Condition tested after loop so statements executed at least once
Similar to PERFORM ... WITH TEST AFTER UNTIL
{ and } unnecessary
The Continue Statement
while (x < 10) {
if (x == 0)
continue;
/* ... */
}
Jumps to the next condition test in innermost for, while or do
The Switch Statement
int n = 2, j, k;
switch (n) {
case 1: case 2:
printf("number is less than 3\n");
break;
case 3:
printf("number is 3\n");
j++;
break;
default:
k++;
break;
}
default: is optional executed if no matching case label is found
Similar to EVALUATE
break exits from innermost for, while, do or switch
if 1st break were left out, code following case 3 would be executed as well
break on default is unnecessary but good programming practice
The Goto Statement
Can be used to jump from one part of the program to another
Used, eg to jump out of nested loops
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
if (a[i] == b[j])
goto found;
/* didn't find any common element */
...
found:
/* got one: a[i] == b[j] */
...
Code involving a goto can always be written without one, though perhaps at the
price of some repeated tests or an extra variable. For example, the array search
becomes
found = 0;
for (i = 0; i < n && !found; i++)
for (j = 0; j < m && !found; j++)
if (a[i] == b[j])
found = 1;
if (found)
/* got one: a[i1] == b[j1] */
...
else
/* didn't find any common element */
makes program difficult to follow use only where absolutely necessary
Data Types
char
int
float
double
void
Modifiers
signed
unsigned
long
short
Operators
Arithmetic
=
+
* multiplication 3 * 4 = 12
/ floatingpoint division 17 / 2 = 8.5
% integer division modulus 17 % 2 = 8
Bitwise
~ NOT
& AND
| OR
^ XOR (exclusive or)
<< left shift
>> right shift
eg
~12 = ~1100 = 11 = 3
12 & 2 = 1100 & 1001 = 1000 = 9
12 | 2 = 1100 | 1001 = 1101 = 13
12 ^ 2 = 1100 ^ 1001 = 0101 = 5
12 << 2 = 1100 << 2 = 110000 = 48
12 >> 2 = 1100 >> 2 = 11 = 3
Compound assignment
i+=; means i = i + 1;
same with =, =, \=, %=, <<=, >>=, &=, |=, ^=
note that
i = i + 1; means i (i + 1);
Type Conversions within Expressions
Implicit Conversions
(1) chars, shorts and enums are converted to ints
signed shorts are converted to unsigned ints
(2) if there is a long double, other type is converted to a long double
(3) if there is a double, other type is converted to a double
(4) if there is a float, other type is converted to a float
(5) if there is an unsigned long, other type is converted to an unsigned long
(6) if there is a long, other type is converted to a long
(7) if there is an unsigned int, other type is converted to an unsigned int
(8) both operands are ints
Explicit Conversions
#include <stdio.h>
main()
{
int i;
float f = 22/7;
i = (int)f;
printf("i = %d\n", i);
}
Symbolic Constants
defines a macro substitution
#define TRUE 1
#define FALSE 0
#if TRUE == FALSE
#undef TRUE /* cancel #definition of TRUE */
#ifdef FALSE /* if FALSE is defined */
#elif /* else if */
#else
#endif
#ifndef TRUE /* if TRUE is not defined */
makes code clearer
by convention, capitals used to distinguish them from variables
# statements are not typechecked
can be used for any type, but be careful of errors
Arrays
main()
{
int i[3];
}
Or
#define MAX 3
main()
{
int i[MAX];
}
Declares an array of 3 integers from i[0] to i[2] (NOT 1 to 3)
Initialised by
i[2] = 4;
Or by aggregate initialiser list in definition
int i[] = {1, 4, 9};
Array size is optional if array is initialised
Arrays of char can be initialised by either of above, or as a character string
char s[] = "Hello\n";
Note that c has 7 characters compiler puts null character '\0' on the end
char s[] = { 'H', 'e', 'l', 'l', 'o', '\n', '\0' };
No need for [] in function call, eg
printf("%s", s);
no need for & when reading an array from scanf(), eg
scanf("&s", s);
comma operator is often used in for loops with arrays, eg to reverse a string
char s[] = "pat";
char temp;
int i, j;
for (i = 0, j = strlen(s) 1; i < j; i++, j)
temp = s[i], s[i] = s[j], s[j] = temp;
operands separated by , are evaluated from left to right
the type and value the expression are the type and value of the right operand
strlen() is a function in <string.h> that returns the length of a char string
/* average.c: */
#include <stdio.h>
double getAverage(int arr[], int size);
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage(balance, 5) ;
printf( "Average value is: %f ", avg );
return 0;
}
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum;
for (i = 0; i < size; ++i)
sum += arr[i];
avg = sum / size;
return avg;
}
Multidimensional arrays
int i[2][3];
declares a 2dimensional array of 2 rows by 3 columns
stored by row, then by column, ie
i[0][0]
i[0][1]
i[0][2]
i[1][0]
i[1][1]
i[1][2]
initialised by
int i[][] = { { 1, 2, 3 },
{ 4, 5, 6 } };
or
i[0][1] = 2;
or
char day[][] = { "mon", "tue", "wed", "thu", "fri", "sat", "sun" };
array sizes not needed when initialised
Pointers
pointers are variables that store the addresses of (point to) other variables
& is the indirection operator &i is the address of variable i
is the dereference operator p is the contents of variable pointed to by p
int i1 = 1, i2; /* variables must be declared beforehand */
int *p1; /* declares p1 as a pointer to an integer */
int *p2 = &i2; /* declares p2 as a pointer to integer i2 */
p1 = &i1; /* assigns the address of i1 to p1 */
p2 = p1; /* p1 and p2 both point to i1 */
i2 = *p1; /* i2 is now equal to i1 */
*p1 = 10; /* i1 and i2 are now equal to 10 */
++*p; /* i1 and i2 are now equal to 11 */
note that
(p)++;
needs ( and ) due to associativity of and ++
p doesn't have to point to anything, it could = NULL (in <stdio.h>)
note that
char p;
declares p as a pointer to a pointer to a char
Pointers to Dynamic Variables
#include <stdio.h>
#include <stdlib.h>
main()
{
char p;
int n;
printf("enter the number of characters you want to store: ");
scanf("%d", &n);
p = calloc(n, sizeof(char));
if (p == NULL) {
printf("error: not enough memory.");
abort();
} else
free(p);
}
more efficient than declaring as array
space needed can be calculated at runtime, not compiletime
dynamically created variables are stored on the heap
dynamic variables save space in executable file as well as memory
sizeof() returns the size of a data type (in bytes)
calloc() allocates space for a number of these variables
calloc() returns a pointer to the first element, or NULL if no space found
abort() exits the program
abort() displays "abnormal program termination" on screen
pointer is not destroyed automatically, so use free()
free() deallocates dynamic variables after use
if space for a single integer, could use
int p = malloc(sizeof(int));
instead
can initialise memory pointed to by p with a character
memset(p, 0, sizeof(char) 10);
usually faster than a for loop
Arrays as Pointers
arrays are stored in contiguous memory locations (= next to each other)
C compiler converts an array to a pointer to the first element,
coding arrays as pointers produces faster machine code
to make enough space, either declare statically (as an array) or dynamically
char p[10];
note that
p; is the same as &p[0];
++p; is the same as p[1];
(p + 3); is the same as p[3];
p + 3; is the same as p[0] + 3;
note that
p++;
does not need ( and )
note that if
char c;
char p;
then
p = c;
and
p++;
are legal, but
c = p;
and
c++;
are not
if
char p1, p2;
then
p2 p1;
returns the number of elements between p1 and p2 (p2 + p1 is illegal)
this number is not necessarily the number of bytes
MultiDimensional Arrays as Pointers
#include <stdio.h>
#include <stdlib.h>
main()
{
int x, y, i, j, temp;
int matrix;
printf("enter the number of columns: ");
scanf("%d", &x);
printf("enter the number of rows: ");
scanf("%d", &y);
if ((matrix = calloc(x y, sizeof(int)) == NULL) {
printf("error: not enough memory\n");
abort();
}
printf("\n");
for (i = 0; i < x; i++) {
temp = i x;
for (j = 0; j < y; j++) {
printf("enter element (%d,%d): ", i + 1, j + 1);
scanf(%d", matrix + temp + j);
}
}
free(matrix);
}
as 2dimensional arrays are stored by column, then row, can code as pointers
matrix is a pointer to an int not a pointer to a pointer to an int
Arrays of Pointers
char day[] = { "monday", "tuesday", "wednesday", "thursday", "friday" };
is an array of strings
accessed by
int i;
for (i = 0; i < 7; i++)
printf("%s\n", day[i]);
coding as a pointer array means that strings can be of different lengths, eg
char day[][] = { "mon", "tues", "wed", "thurs", "fri" };
every day would be allocated 10 characters (= enough to hold "wed\0")
Pointers to Arrays
int (*i)[10];
is a pointer to an array of 10 integers
used when the size of each argument is the same but their number is not known
Pointers to Pointers
#include <stdio.h>
main()
{
int x, *p, **q;
x = 10;
p = &x;
q = &p;
printf("%d", **q); /* print the value of x */
}
compiler converts 2D arrays, arrays of pointers and pointers to arrays, eg
char *day[] = { "monday", "tuesday", "wednesday", "thursday", "friday" };
is converted to
char **day = { "monday", "tuesday", "wednesday", "thursday", "friday" };
note that
*day; /* = string "monday" */
**day; /* = 'm' in "monday" */
*(*day + 1); /* = 'o' in "monday" */
*(*(day + 2) + 3); /* = 'n' in "wednesday" */
**++day; /* = 't' in "tuesday" */
*++day; /* = string "tuesday" */
accessed by
int i;
for (i = 0; i < 7; i++)
printf("%s\n", *line++);
used when neither the size nor number of arguments is known at compiletime
Functions
(procedural) abstraction = hiding complexity
information hiding = access data only via functions safer/more maintainable
/* hello2.c: displays "hello" message using a call to a function */
#include <stdio.h>
void hello(void);
main()
{
hello();
}
/* hello(): displays "hello" message on screen */
void hello(void)
{
printf("hello\n");
}
main() is conventionally first function defined (= topdown approach)
prototype (declare) hello() before call if definition appears after call
should use comments above all function definitions (except the simplest)
a function can receive arguments from, and return a value to, its caller
The value supplied by the caller is an argument
The value received by the function is a parameter
compiler typechecks (number/type of arguments + return type) function + call
main() not properly typechecked as its caller is not known at compiletime
void means no value is returned from the function
(void) means no arguments are passed to the function
Functions Returning Values
#include <stdio.h>
int sum(int, int);
main()
{
int n, total;
printf("Enter a number:\n");
scanf("%d", &n);
total = sum(n, 1);
printf("%d + 1 = %d\n", n, total);
}
int sum(int n1, int n2)
{
return n1 + n2;
}
No need for argument names in prototype, just their types
Can have more than one return statement in a function
Could use return in a switch statement instead of break
Could use return (a + b); instead
could have return; in function of return type void (but can be ommitted)
default return type is int (but specify anyway)
main() can return a value usually, int 0 means success, 1 means failure
if value was not requested, operating system ignores it
could rewrite function call as
printf("%d + 1 = %d\n", first, 1, sum(first, second));
Recursive Functions
#include <stdio.h>
int fac(int);
main()
{
int i;
for (i = 1; i <= 5; i++)
printf("%d! = %d\n", i, fac(i));
}
int fac(int i)
{
int n = 1;
if (i != 0)
n = i fac(i 1);
return n;
}
A function can call itself
It must, however, be able to escape from infinite recursion, eg if statement
Mutual recursion f1() calls f2() and f2() calls f1()
Indirect recursion f1() calls f2(), f2() calls f3() and f3() calls f1()
n is a local variable it can only be used in fac()
Local variables are stored on the stack
Global variables are declared outside any function
They can be used anywhere in the source file
Global variables are stored in the program
Pointers as Function Arguments
"call by value" = copy of arguments passed to functions, not original value
therefore, functions cannot change the value of an argument
can change values by passing address of argument instead
#include <stdio.h>
void swap(int *, int *);
main()
{
int a, b;
printf("Enter 1st integer: ");
scanf("%d", &a);
printf("Enter 2nd integer: ");
scanf("%d", &b);
swap(&a, &b);
printf("The two integers reversed are %d and %d", a, b);
}
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
main() passes pointers to 2 integers, swap() receives the contents of pointers
Arrays as Function Arguments
#include <stdio.h>
void copy(int [], int []);
main()
{
int i, a[4], b[4];
for (i = 0; i <= 3; i++)
a[i] = 0;
copy(a, b);
}
void copy(int from[], int to[])
{
int i;
for (i = 0; i <= 3; i++)
from[i] = to[i];
}
as array is converted into a pointer, no need for [] in call
also, no need for 1D array size in definition
likewise, no need for & in call or * in definition if function changes array
be careful when a function is not meant to change the array
a for loop within a for loop is often used with 2D arrays, eg
void printlines(char x[][10])
{
int i, j;
for (i = 0, i < 10; i++) {
for (j = 0; j < 10; j++)
printf(%s\t", x[i][j]);
printf("\n");
}
}
for multidimensional arrays, no need for 1st size in definition
if 1st size is needed, pass it as a separate argument, eg
void printmat(int matrix[][10], int d1)
{
int i, j;
for (i = 0; i < d1; i++) {
for (j = 0; j < 10; j++)
printf("%5d", m[i][j]);
printf("\n");
}
}
must give other sizes so compiler can calculate addresses
if other sizes are not known at compiletime pass as pointer to pointer
void printmat(int **matrix, int d1, int d2)
{
int i, j;
for (i = 0; i < d1; i++) {
for (j = 0; j < d2; j++)
printf("%5d", ((int *)matrix)[i d2 + j]);
printf("\n");
}
}
note that (int *)m is an explicit type conversion
could be rewritten more clearly as
int *m = (int *)matrix
/* ... */
v[i d2 + j]
when passing an array of pointers, no sizes are needed, ie
void f(char *[]);
same for a pointer to an array, eg
void g(char (*)[]);
Functions Returning Pointers
#include <stdio.h>
#include <string.h>
int *largeint(int, int);
char *longword(char *, char *);
main()
{
int i1 = 1, i2 = 2;
char *s1 = "John", *s2 = "Smith";
printf("larger integer is %d\n", *largeint(&i1, &i2));
printf("longer word is %s\n", longword(s1, s2));
}
int *largeint(int *i1, int *i2)
{
return (*i1 >= *i2) ? i1 : i2;
}
char *longword(char *s1, char *s2)
{
return (strlen(s1) >= strlen(s2)) ? s1 : s2;
}
note that string longword does not need * in function call but largeint does
do not return a pointer to a local as it might not exist after function
Pointers to Functions
#include <stdio.h>
void hello(void);
main()
{
void (*pf)(void);
pf = hello;
(*pf)();
}
void hello(void)
{
printf("hello\n");
}
dereferencing a pointer to a function calls that function
note that pf() can be called by
pf();
and that hello could be assigned to pf by
void (*pf)(void) = &hello;
note that
char *(*f)(void);
is a pointer to a function returning a pointer to a char
Arrays of Pointers to Functions
#include <stdio.h>
void f1(void);
void f2(void);
void f3(void);
main()
{
int choice;
void (*apf[])(void) = { f1, f2, f3 };
printf("Enter choice 1, 2 or 3: ");
scanf("%d", &choice);
if (choice >= 1 && choice <= 3)
(apf[choice 1])();
else
printf("error\n");
}
void f1(void)
{
printf("This is function one\n");
}
void f2(void)
{
printf("This is function two\n");
}
void f3(void)
{
printf("This is function three\n");
}
use array of pointers for faster code and less of it
note that apf() can be called by
apf[choice 1]();
as well
Pointers to Functions as Function Arguments
#include <stdio.h>
void tab(int (*)(int));
int square(int);
int cube(int);
int quad(int);
main()
{
printf("squares\n\n);
tab(square);
printf("\ncubes\n\n");
tab(cube);
printf("\nquads\n\n");
tab(quad);
}
void tab(int (*f)(int))
{
int n;
for (n = 1; n <= 10; n++)
printf("%10\td%10d\n", n, f(n));
}
int square(int n)
{
return n * n;
}
int cube(int n)
{
return n * n * n;
}
int quad(int n)
{
return n * n * n * n;
}
can pass a pointer to a function as an argument to another function
Variadic Functions
the number of arguments to a function can be set by its caller
this is how printf, etc. works
#include <stdio.h>
#include <stdarg.h>
int sum(int, ...);
main()
{
printf("%d + %d = %d\n", 10, 20, sum(2, 10, 20));
printf("%d + %d + %d = %d\n", 10, 20, 30, sum(3, 10, 20, 30));
}
int sum(int number, ...)
{
va_list args;
int arg, k, total = 0;
va_start(args, number)
for (k = 0; k < number; k++) {
arg = va_arg(args, int);
total += arg;
}
va_end(args);
return total;
}
type va_list and macros va_start, va_arg and va_end defined in <stdarg.h>
va_start sets pointer to 1st unnamed argument (ie after number)
va_arg returns the next argument in the list (of type int, in this case)
va_end must be called to clean things up in sum() before returning to main()
#include <stdio.h>
#include <stdarg.h>
void report(char *, ...);
main()
{
int i = 10;
report("Message i = %d\n", i)
}
void report(char *format, ...)
{
va_list args;
printf("Error.\n");
va_start(args, format);
vprintf(format, args);
va_end(args);
}
vprintf() uses a pointer to the argument list as opposed to the list itself
Void Pointers
#include <stdio.h>
#include <string.h>
void swap(void *, void *, size_t);
main()
{
int i1 = 1, i2 = 2;
char s1[] = "One", s2[] = "Two";
printf("i1 = %d, i2 = %d\n", i1, i2);
printf("s1 = %s, s2 = %s\n", s1, s2);
swap((void *) i1, (void *) i2, sizeof(int));
swap((void *) s1, (void *) s2, strlen(s1));
printf("i1 = %d, i2 = %d\n", i1, i2);
printf("s1 = %s, s2 = %s\n", s1, s2);
}
void swap(void *v1, void *v2, size_t n);
{
unsigned char *p1, *p2;
p1 = v1;
p2 = v2;
for (; n > 0; n) {
*p1 ^= *p2;
*p2 ^= *p1;
*p1++ ^= *p2++;
}
}
a void pointer cannot be dereferenced (hence *p1, *p2)
generic type = one which can be used for any type
Command Line Arguments
/* echo.c */
#include <stdio.h>
main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
printf("arg%d = %s\n", argc, argv[i];
}
used to pass arguments from operating system to main()
argc = conventional name for no of arguments passed including the program name
argv is conventionally an array of character strings (incl the program name)
last argument in argv is NULL
called by
$echo hello hello
argv can be represented as a pointer to a pointer to a char, ie
#include <stdio.h>
main(int argc, char **argv)
{
**argc;
while (**argc > 0)
printf("%s\n", *++argv);
}
Function Macros
#define ACCEPTINTEGER(I) scanf("%d", &I)
#define SWAPINT(X, Y) { int temp = X; x = Y; Y = temp; }
#define ISLEAP(Y) { Y % 4 == 0 && Y % 100 != 0 && Y % 400 == 0 }
#define SQUARE(X) ((X) * (X))
if code extends over more than 1 line, last character on line must be \
can have \ in the middle of a character string
extra ( and ) in SQUARE to override precedence
can also use
#define FOR (CONTROL, INIT, FINAL) for ((CONTROL) = (INIT);\
(CONTROL) <= (FINAL);\
(CONTROL)++;
is the same as
FOR (i, 1, 10)
is the same as
for (i = 1; i <= 10; i++)
The System Function
defined in <stdlib.h>
int system(char *);
executes operating system commands within C program
/* call.c: calls program "hello2.c" */
#include <stdlib.h>
#include <stdio.h>
main()
{
int i
i = system("hello");
if (i == 0)
printf("ok\n");
else
printf("error\n");
}
where hello is defined as
/* hello2.c: called by program "call" */
#include <stdio.h>
main()
{
printf("hello\n");
}
The Exit Function
defined in <stdlib.h>
void exit(int status);
same effect as return statement in main() but can be called from any function
closes all files, etc abort() does not
status can be a number, eg 0, or predefined EXIT_SUCCESS or EXIT_FAILURE
The Atexit Function
defined in <stdlib.h>
int atexit(void (*fcn)(void));
lists function(s) to be called by a successful exit()
Const
const int i = 1;
once set, the value i cannot be changed
int is the default for a const, so it can be ommitted
if not initialised, compiler does it, eg ints = 0
produces faster machine code
Const and Pointers
to make pointer constant (pc always points to c1)
char c1 = 'x', c2 = 'y';
char *const p = &c1;
so we can use *p = 'a'; but we cannot use p = &c2;
to make pc point to a const
const char c1 = 'x', c2 = 'y';
const char *p = &c1;
so we can use p = &c2; but we cannot use *p = 'a';
to declare a const pointer to a const
const char c1 = 'x', c2 = 'y';
const char const *p = &c1;
so we cannot use either p = &c2; or *p = 'a';
Const Function Arguments
#include <stdio.h>
void copy(char *, const char *);
/* tests copy function */
main()
{
char s1[] = "hello", s2[6];
copy(s2, s1);
printf("s1 = &s\n", s1);
printf("s2 = %s\n", s2);
}
/* copies string s2 to string s1 */
void copy(char *s1, const char *s2)
{
while (*s1++ = *s2++);
}
declaring pointer s2 as const means copy() cannot change the value of s2
note that all the processing is carried out in the while condition
the loop consists of the null statement;
could declare arguments as character arrays
void copy(char [], const char []);
Const Functions
const int sum(const int, const int);
/* ... */
const int sum(const int i1, const int i2)
{
return i1 + i2;
}
the return value of a const function cannot be changed by its caller
Extern
/* main.c */
#include <stdio.h>
int i; /* definition */
main()
{
i = 10;
printf("external i = %d.", i);
}
/* sub.c */
extern int i; /* declaration */
void f(void)
{
printf("i = &d\n", i);
}
should use a comment for each external (global) variable
extern declaration means defined in another source file or later in this one
can use extern for function declarations (eg in .h files) but don't have to
Auto
auto int fred;
means fred is local (automatic) the default
Static
#include <stdio.h>
void f(void)
main()
{
int j;
printf("s\t\t\n\n");
for (j = 0; j < 5; j++)
f();
}
void f(void)
{
static int s = 1;
int i = 1;
printf("%d\t\t%d\n", s, i);
s++;
i++;
}
prints
s i
1 1
2 1
3 1
4 1
5 1
local static variables remain in existence after the end of the function call
cannot be used outside the function
initialisations only executed on first call to function
if you don't initialise statics, the compiler does it for you, eg int = 0
statics produce faster machine code but more of it
static variables are stored in the program, not on the stack
better for local variables that change value many times in same function call
could be used for returning pointers to local variables from functions, eg
char *longword(char *s1, char *s2)
{
static char *temp;
if (strlen(s1) >= strlen(s2))
temp = s1;
else
temp = s2;
return temp
}
global static variables and functions cannot be accessed from any other file
if used only by user's functions, define before call, no need for declaration
static int f(void)
{
}
Register
register int fred;
MIGHT put fred into fastaccess register
can be used in formal argument list but NOT for any globals or statics
cannot take the address of a register variable
Volatile
volatile int fred;
value might change without computer's knowledge use for hardware
Header Files
searches for #include "myheader.h" in current directory
put function definitions in myheader.c, compile and then link with main prog
standard #include <...> header files found in include\ directory
automatically links standard library .lib object files in lib\ directory
to prevent header being included more than once
/* myhead.h */
#ifndef _myhead
#define _myhead
#include <stdio.h>
#include <stdlib.h>
#include "myhead.h"
#include "otherhd.h"
#define SWAPINT(X, Y) { int temp = X; x = Y; Y = temp; }
#define A 1
const int i = 1; /* global variable */
void f(int);
#endif
Typedef
typedef int Length;
then
Length len;
instead of
int len;
for clearer code
can also use
typedef char *String[80];
String s1, s2;
instead of
char s1[80], s2[80];
Enum
#include <stdio.h>
enum colours { RED, YELLOW = 2, BLUE };
main()
{
enum colours c;
if (c == RED)
printf("c is 0")
else if (c == YELLOW)
printf("c is 2")
else
printf("c is 3");
}
for clearer code
not properly typechecked like const, but better than #define
a boolean is an expression that is either true or false
#include <stdio.h>
enum bool = { FALSE = 0, TRUE = 1 };
bool ispos(int);
main()
{
if (ispos(2))
printf("2 is positive\n");
}
bool ispos(int i)
{
bool b = TRUE;
if (i <= 0)
b = FALSE;
return b;
}
Struct
struct coordinate
{
int x;
int y;
};
structs (and unions and typedefs) declared outside all function definitions
struct coordinate point;
declares variable point to be of type coordinate
or shortened to
struct coordinate {
int x;
int y;
} point;
for global variable
use coordinate if more variables will be declared
accessed by
struct coordinate point;
point.x = 1;
or by aggregate initialiser list
struct coordinate point = { 1, 2 };
can use with typedefs
typedef struct {
int i;
char c;
} mystruct;
accessed by
mystruct s;
s.i = 10;
Arrays of Structures
struct coord {
int i;
char c;
} point[100];
printf("%d", point[7].i);
Pointers to Structures
declaring a pointer to a struct means less machine code and faster execution
same for other large data types
for
struct fred {
int x
/* ... */
}
and
struct fred *f;
note that
(*f).x;
could be written
f>x;
Structs and Functions
struct s {
int i;
double d;
};
struct s f(struct s);
main()
{
struct s s1, s2;
s1.i = 10;
s1.d = 3.14;
s2 = f(s1);
}
struct s f(struct s s1)
{
struct s temp;
temp.i = 2 s1.i;
temp.d = 3 s1.d;
return temp;
}
but could use typedef
typedef struct {
int i;
double d;
} Mystruct;
Mystruct f(Mystruct s1)
{
/* ... */
}
SelfReferential Structures
Linear linked lists
a struct can elements that point to other structs of the same type
can be used to implement a linkedlist
#include <stdio.h>
enum bool = { FALSE = 0, TRUE = 1 };
typedef struct node {
int data;
struct node *next;
} *Node;
typedef struct list {
struct node *head;
int length;
} *List;
void error(const char *s)
{
printf("%s", s);
exit(1);
}
void newlist(List l)
{
}
void display(List l)
{
Node temp = (Node)malloc(sizeof(Node));
for (current = L>head; current != NULL; current = current>next)
printf("%d\n", current>data);
}
bool isempty(List l)
{
return l>head == NULL;
}
int length(List l)
{
return l>length;
}
int isin(List l, int data)
{
Node current = (Node)malloc(sizeof(Node));
current = l>head;
while ((current != NULL) && (data != current>data))
current = current>next;
return current != NULL;
}
void insert(List l, int i)
{
Node current = (Node)malloc(sizeof(Node));
current = l>head;
current>data = i;
while (current != NULL) {
if (current>data > n>data) {
n>next = l>current>next;
l>currentnext = n>next;
break;
}
current = l>current>next;
}
}
void remove(List l, int data)
{
Node current = (Node)malloc(sizeof(Node));
current = l>head
}
void append(List l1, List l2)
{
}
void merge(List l1, List l2)
{
}
void reverse(List l)
{
}
int ispal(List l)
{
}
int isanag(List l)
{
}
int sort(List l)
{
}
can be used to create a linked list of nodes
more efficient than an array of structs as list can grow/shrink with program
also makes inserting/deleting nodes easier
doublylinked list has pointers to both previous and next nodes
singlylinked list has pointers to either previous or next node
to implement a generic stack (last infirst out)
Circular lists
Stacks
#include <stdio.h>
enum bool = { FALSE = 0, TRUE = 1 };
typedef void *Data;
typedef struct node {
void* data;
struct node* below;
} *Node;
typedef struct stack {
struct node *bottom;
int numelem;
struct node *top;
} *Stack;
void error(const char *s)
{
printf("%s", s);
exit(1);
}
bool isempty(Stack S)
{
return S>top == NULL;
}
Data top(Stack S)
{
return S>top>data;
}
Data pop(STACK S)
{
static void *current = S>top>data;
S>top = S>top>below;
return current;
}
void push(STACK s, void data)
{
}
Queues
queues are first infirst out
enum bool = { FALSE = 0, TRUE = 1 };
typedef struct node {
struct node *previous;
int data;
struct node *next;
} Node;
typedef struct queue {
struct node *front;
int length;
struct node *back;
} Queue;
void error(const char *s)
{
printf("%s", s);
exit(1);
}
Data front(Queue Q)
{
return Q>back>data;
}
void join(Queue Q, int data)
{
}
data leave(Queue Q)
{
if (n>data == Q>front>data)
q>fr
}
a tree node has a singlylinked list of subtrees
enum bool = { FALSE = 0, TRUE = 1 };
typedef struct node {
struct node *parent;
int data;
struct nodelist *subtree;
} *Node;
typedef struct nodelist {
struct node *head;
int numelem;
} *Nodelist;
typedef struct tree {
struct node *root;
int numelem;
} *Tree;
void error(const char *s)
{
printf("%s", s);
exit(1);
}
Binary trees
have at most 2 subtrees
can be used for storing sorted data
enum bool = { FALSE = 0, TRUE = 1 };
typedef struct node {
struct node *parent;
int data;
struct node *leftchild;
struct node *rightchild;
} *Node;
typedef struct binarysearchtree {
struct node *root;
int numelem;
} *BinarySearchTree;
void error(const char *s)
{
printf("%s", s);
exit(1);
}
Graphs
consist of nodes connected by arcs
data can be stored in both nodes and arcs
a graph is a mutuallyrecursive stucture
enum bool = { FALSE = 0, TRUE = 1 };
typedef struct node {
int data;
struct arclist *arcs;
} *Node;
typedef struct arc {
int data;
struct node *next;
} *Arc;
typedef struct arclist {
struct arc *head;
int numelem;
} *Arclist;
typedef struct graph {
struct node *first;
int numelem;
} *Graph;
void error(const char *s)
{
printf("%s", s);
exit(1);
}
void display(void)
{
}
void addnode(Graph g)
{
}
void addarc(Graph g)
{
}
void removenode(Graph g)
{
}
void removearc(Graph g)
{
}
lists, stacks and queues are linear structures, trees and graphs are not
BitFields
struct flags {
unsigned int iskey : 1;
unsigned int isext : 1;
unsigned int isstat : 1;
};
used for saving memory
each field is 1 bit long can store either 0 or 1
accessed by
struct flags f;
f.iskey = 0;
Union
union u {
int i;
char c;
} diff;
diff can hold EITHER on int
diff.i = 1;
OR a char
diff.c = 'a';
other rules same as struct
The sizeof() operator
sizeof(double);
operator returns the number of bytes used to store a variable of type double
as storage varies between types of computer
operator can be used for any type long, struct mystruct, etc
Predefined symbollic constants
__FILE__ eg "myprog.c"
__LINE__ of source code
__DATE__ compilation date, eg "Jan 01 1900"
__TIME__ compilation time, eg "16:04:59"
__STDC__ = 1 if compiler conforms to ANSI C Standard
short <= int <= long
float <= double
signed by default
unsigned int/short/long eg if signed = 128 128, unsigned = 0 256
int is optional short = short int, unsigned long int = unsigned long, etc
Files
5 standard I/O streams opened automatically
stdin input keyboard
stdout output monitor
stdprn parallel port (LPT1) printer
stdaux serial port (COM) modem/another computer
stderr error messages monitor
eg
fprintf(stdprn, "This message will be displayed on the printer\n");
note that
fprintf(stdout, "Hello %d", 1);
is the same as
printf("Hello %d", 1);
to declare a variable fp as a pointer to a file
FILE *fp;
to open a file
fp = fopen("myfile.dat", "r");
function fopen opens file fp and calls it "myfile.dat"
"r" opens existing file at beginning for reading
"r+" same as "r" but for writing as well after first read
"w" creates new file or deletes all data in existing one for writing
"w+" same as "w' but for reading as well after first write
"a" creates new file or appends to existing one for writing
"a+" same as "a" but for reading as well after first write
error caused if "r" or "r+" file does not exist
usually trapped by
if ((fp = fopen("myfile.dat", "r")) == NULL)
{
printf("Error: cannot open file \"myfile.dat\"\n.")
abort();
}
to redirect output to a file
freopen("myfile.dat", "w", stdout);
printf("This line will appear in \"myfile.dat\" not the screen\n");
to close a file
fclose(fp);
to close all nonstandard files
fcloseall();
to delete a file from disk
remove("myfile.dat");
to rename a file
rename("oldname.txt", "newname.txt");
to read the next character from fp and place it in variable c
c = fgetc(fp);
to write the value of variable c into fp
fputc(c, fp);
to test whether or not the next character in fp is the end of file character
if (feof(fp))
/* ... */;
to write "Hello 1" to fp
fprintf(fp, "Hello %d", 1);
to read floating point number from fp and puts it in variable real
fscanf(fp, "%f", &real);
Keywords
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
Operator Precedence
() [] > .
! ~ ++ + * & (type) sizeof r l
* / %
+
<< >>
<<= >>=
== !=
&
^
|
&&
||
?:
r l
= += = = /= %= &= ^= |= <<= >>= r
l ,
,
All others associate l r
associativity = two operators of equal precedence in same statement
1st (left to right)
() function arguments
[] array
> pointer to structure member
. stucture reference
2nd
unary minus
+ unary plus
++ increment
decrement
! logical negation
~ 1's complement
pointer reference (indirection)
& pointer derefernce (address)
sizeof size of an object
3rd
(type) type cast (coercion)
multiplication
/ division
% modulus
+ addition
subtraction
4th
<< left shift
>> right shift
5th
< less than
<= less than or equal to
> greater than
>= greater than or equal to
6th
== equality
!= inequality
7th
& bitwise AND
^ bitwise XOR
| bitwise OR
&& logical AND
| logical OR
? : conditional expression
= assignment operators
= special assignment operators
/=
%=
+=
*=
&=
^=
|=
<<=
>>=
, comma operator
Standard library functions
#include <ctype.h>
int isalnum(int c); /* is c in az, AZ or 09? */
int isalpha(int c); /* is c in az or AZ? */
int iscntrl(int c); /* is c a control character (eg FF, HT, NL)? */
int isdigit(int c); /* is c in 09 (decimal)? */
int isgraph(int c); /* is c a printable character EXCEPT space? */
int islower(int c); /* is c in az? */
int isprint(int c); /* is c a printable character? */
int ispunct(int c); /* is c punctuation (not space)? */
int isspace(int c); /* is c CR, FF, HT, NL, VT or space? */
int isupper(int c); /* is c in AZ? */
int isxdigit(int c); /* is c in 09, AF or af (hex)? */
int tolower(int c); /* A L a, b L b */
int toupper(int c); /* a L A, B L B */
#include <math.h>
double sin(double x);
double cos(double x);
double tan(double x);
double asin(double x); /* e [p/2, p/2], x e [1, 1] */
double acos(double x); /* e [0, p], x e [1, 1] */
double atan(double x); /* e [p/2, p/2] */
double atan2(double y, double x); /* e [p, p] */
double sinh(double x);
double cosh(double x);
double tanh(double x);
double exp(double x); /* = e to the power of x */
double log(double x); /* = ln x */
double log10(double x); /* = log x */
double pow(double x, double y); /* = x to the power of y */
double sqrt(double x); /* = square root of x */
double ceil(double x); /* smallest int >= x */
double floor(double x); /* largest int <= x */
double fabs(double x); /* = |x|, fabs(3)=3 */
#include <stdlib.h>
double atof(const char s); /* converts s[] to a double */
int atoi(const char s); /* converts s[] to an int */
long atol(const char s); /* converts s[] to a long */
#include <stdio.h>
The stdio header provides functions for performing input and output.
Macros:
NULL
_IOFBF
_IOLBF
_IONBF
BUFSIZ
EOF
FOPEN_MAX
FILENAME_MAX
L_tmpnam
SEEK_CUR
SEEK_END
SEEK_SET
TMP_MAX
stderr
stdin
stdout
Functions:
clearerr();
fclose();
feof();
ferror();
fflush();
fgetpos();
fopen();
fread();
freopen();
fseek();
fsetpos();
ftell();
fwrite();
remove();
rename();
rewind();
setbuf();
setvbuf();
tmpfile();
tmpnam();
fprintf();
fscanf();
printf();
scanf();
sprintf();
sscanf();
vfprintf();
vprintf();
vsprintf();
fgetc();
fgets();
fputc();
fputs();
getc();
getchar();
gets();
putc();
putchar();
puts();
ungetc();
perror();
Variables:
typedef size_t
typedef FILE
typedef fpos_t
Variables and Definitions
size_t is the unsigned integer result of the sizeof keyword.
FILE is a type suitable for storing information for a file stream.
fpos_t is a type suitable for storing any position in a file.
NULL is the value of a null pointer constant.
_IOFBF, _IOLBF, and _IONBF are used in the setvbuf function.
BUFSIZ is an integer which represents the size of the buffer used by the setbuf
function.
EOF is a negative integer which indicates an endoffile has been reached.
FOPEN_MAX is an integer which represents the maximum number of files that the
system can guarantee that can be opened simultaneously.
FILENAME_MAX is an integer which represents the longest length of a char array
suitable for holding the longest possible filename. If the implementation
imposes no limit, then this value should be the recommended maximum value.
L_tmpnam is an integer which represents the longest length of a char array
suitable for holding the longest possible temporary filename created by the
tmpnam function.
SEEK_CUR, SEEK_END, and SEEK_SET are used in the fseek function.
TMP_MAX is the maximum number of unique filenames that the function tmpnam can
generate.
stderr, stdin, and stdout are pointers to FILE types which correspond to the
standard error, standard input, and standard output streams.
Streams and Files
Streams facilitate a way to create a level of abstraction between the program
and an input/output device. This allows a common method of sending and receiving
data amongst the various types of devices available. There are two types of
streams: text and binary.
Text streams are composed of lines. Each line has zero or more characters and
are terminated by a newline character which is the last character in a line.
Conversions may occur on text streams during input and output. Text streams
consist of only printable characters, the tab character, and the newline
character. Spaces cannot appear before a newline character, although it is
implementationdefined whether or not reading a text stream removes these
spaces. An implementation must support lines of up to at least 254 characters
including the newline character.
Binary streams input and output data in an exactly 1:1 ratio. No conversion
exists and all characters may be transferred.
When a program begins, there are already three available streams: standard
input, standard output, and standard error.
Files are associated with streams and must be opened to be used. The point of
I/O within a file is determined by the file position. When a file is opened, the
file position points to the beginning of the file unless the file is opened for
an append operation in which case the position points to the end of the file.
The file position follows read and write operations to indicate where the next
operation will occur.
When a file is closed, no more actions can be taken on it until it is opened
again. Exiting from the main function causes all open files to be closed.
File Functions
clearerr
Declaration:
void clearerr(FILE stream);
Clears the endoffile and error indicators for the given stream. As long as the
error indicator is set, all stream operations will return an error until
clearerr or rewind is called.
fclose
Declaration:
int fclose(FILE stream);
Closes the stream. All buffers are flushed.
If successful, it returns zero. On error it returns EOF.
feof
Declaration:
int feof(FILE stream);
Tests the endoffile indicator for the given stream. If the stream is at the
endoffile, then it returns a nonzero value. If it is not at the end of the
file, then it returns zero.
ferror
Declaration:
int ferror(FILE stream);
Tests the error indicator for the given stream. If the error indicator is set,
then it returns a nonzero value. If the error indicator is not set, then it
returns zero.
fflush
Declaration:
int fflush(FILE stream);
Flushes the output buffer of a stream. If stream is a null pointer, then all
output buffers are flushed.
If successful, it returns zero. On error it returns EOF.
fgetpos
Declaration:
int fgetpos(FILE stream, fpos_t pos);
Gets the current file position of the stream and writes it to pos.
If successful, it returns zero. On error it returns a nonzero value and stores
the error number in the variable errno.
2.12.3.7 fopen
Declaration:
FILE fopen(const char filename, const char mode);
Opens the filename pointed to by filename. The mode argument may be one of the
following constant strings:
r read text mode
w write text mode (truncates file to zero length or creates new file)
a append text mode for writing (opens or creates file and sets file
pointer to the endoffile)
rb read binary mode
wb write binary mode (truncates file to zero length or creates new
file)
ab append binary mode for writing (opens or creates file and sets file
pointer to the endoffile)
r+ read and write text mode
w+ read and write text mode (truncates file to zero length or creates
new file)
a+ read and write text mode (opens or creates file and sets file
pointer to the endoffile)
r+b or rb+ read and write binary mode
w+b or wb+ read and write binary mode (truncates file to zero length or creates
new file)
a+b or ab+ read and write binary mode (opens or creates file and sets file
pointer to the endoffile)
If the file does not exist and it is opened with read mode (r), then the open
fails.
If the file is opened with append mode (a), then all write operations occur at
the end of the file regardless of the current file position.
If the file is opened in the update mode (+), then output cannot be directly
followed by input and input cannot be directly followed by output without an
intervening fseek, fsetpos, rewind, or fflush.
On success a pointer to the file stream is returned. On failure a null pointer
is returned.
2.12.3.8 fread
Declaration:
size_t fread(void ptr, size_t size, size_t nmemb, FILE stream);
Reads data from the given stream into the array pointed to by ptr. It reads
nmemb number of elements of size size. The total number of bytes read is (size
nmemb).
On success the number of elements read is returned. On error or endoffile the
total number of elements successfully read (which may be zero) is returned.
2.12.3.9 freopen
Declaration:
FILE freopen(const char filename, const char mode, FILE stream);
Associates a new filename with the given open stream. The old file in stream is
closed. If an error occurs while closing the file, the error is ignored. The
mode argument is the same as described in the fopen command. Normally used for
reassociating stdin, stdout, or stderr.
On success the pointer to the stream is returned. On error a null pointer is
returned
fseek
int fseek(FILE stream, long int offset, int whence);
Sets the file position of the stream to the given offset. The argument offset
signifies the number of bytes to seek from the given whence position. The
argument whence can be:
SEEK_SET Seeks from the beginning of the file.
SEEK_CUR Seeks from the current position.
SEEK_END Seeks from the end of the file.
On a text stream, whence should be SEEK_SET and offset should be either zero or
a value returned from ftell.
The endoffile indicator is reset. The error indicator is NOT reset.
On success zero is returned. On error a nonzero value is returned.
fsetpos
int fsetpos(FILE stream, const fpos_t pos);
Sets the file position of the given stream to the given position. The argument
pos is a position given by the function fgetpos. The endoffile indicator is
cleared.
On success zero is returned. On error a nonzero value is returned and the
variable errno is set.
ftell
long int ftell(FILE stream);
Returns the current file position of the given stream. If it is a binary stream,
then the value is the number of bytes from the beginning of the file. If it is a
text stream, then the value is a value useable by the fseek function to return
the file position to the current position.
On success the current file position is returned. On error a value of 1L is
returned and errno is set.
fwrite
size_t fwrite(const void ptr, size_t size, size_t nmemb, FILE stream);
Writes data from the array pointed to by ptr to the given stream. It writes
nmemb number of elements of size size. The total number of bytes written is
(sizenmemb).
On success the number of elements writen is returned. On error the total number
of elements successfully writen (which may be zero) is returned.
remove
int remove(const char filename);
Deletes the given filename so that it is no longer accessible (unlinks the
file). If the file is currently open, then the result is implementationdefined.
On success zero is returned. On failure a nonzero value is returned.
rename
int rename(const char old_filename, const char new_filename);
Causes the filename referred to by old_filename to be changed to new_filename.
If the filename pointed to by new_filename exists, the result is implementation
defined.
On success zero is returned. On error a nonzero value is returned and the file
is still accessible by its old filename.
rewind
void rewind(FILE stream);
Sets the file position to the beginning of the file of the given stream. The
error and endoffile indicators are reset.
setbuf
void setbuf(FILE stream, char buffer);
Defines how a stream should be buffered. This should be called after the stream
has been opened but before any operation has been done on the stream. Input and
output is fully buffered. The default BUFSIZ is the size of the buffer. The
argument buffer points to an array to be used as the buffer. If buffer is a null
pointer, then the stream is unbuffered.
setvbuf
int setvbuf(FILE stream, char buffer, int mode, size_t size);
Defines how a stream should be buffered. This should be called after the stream
has been opened but before any operation has been done on the stream. The
argument mode defines how the stream should be buffered as follows:
_IOFBF Input and output is fully buffered. If the buffer is empty, an input
operation attempts to fill the buffer. On output the buffer will be completely
filled before any information is written to the file (or the stream is closed).
_IOLBF Input and output is line buffered. If the buffer is empty, an input
operation attempts to fill the buffer. On output the buffer will be flushed
whenever a newline character is written.
_IONBF Input and output is not buffered. No buffering is performed.
The argument buffer points to an array to be used as the buffer. If buffer is a
null pointer, then setvbuf uses malloc to create its own buffer.
The argument size determines the size of the array.
On success zero is returned. On error a nonzero value is returned.
tmpfile
FILE tmpfile(void);
Creates a temporary file in binary update mode (wb+). The tempfile is removed
when the program terminates or the stream is closed.
On success a pointer to a file stream is returned. On error a null pointer is
returned.
tmpnam
char tmpnam(char str);
Generates and returns a valid temporary filename which does not exist. Up to
TMP_MAX different filenames can be generated.
If the argument str is a null pointer, then the function returns a pointer to a
valid filename. If the argument str is a valid pointer to an array, then the
filename is written to the array and a pointer to the same array is returned.
The filename may be up to L_tmpnam characters long.
Formatted I/O Functions
..printf Functions
Declarations:
int fprintf(FILE stream, const char format, ...);
int printf(const char format, ...);
int sprintf(char str, const char format, ...);
int vfprintf(FILE stream, const char format, va_list arg);
int vprintf(const char format, va_list arg);
int vsprintf(char str, const char format, va_list arg);
The ..printf functions provide a means to output formatted information to a
stream.
fprintf sends formatted output to a stream
printf sends formatted output to stdout
sprintf sends formatted output to a string
vfprintf sends formatted output to a stream using an argument list
vprintf sends formatted output to stdout using an argument list
vsprintf sends formatted output to a string using an argument list
These functions take the format string specified by the format argument and
apply each following argument to the format specifiers in the string in a left
to right fashion. Each character in the format string is copied to the stream
except for conversion characters which specify a format specifier.
The string commands (sprintf and vsprintf) append a null character to the end of
the string. This null character is not counted in the character count.
The argument list commands (vfprintf, vprintf, and vsprintf) use an argument
list which is prepared by va_start. These commands do not call va_end (the
caller must call it).
A conversion specifier begins with the % character. After the % character come
the following in this order:
[flags] Control the conversion (optional).
[width] Defines the number of characters to print (optional).
[.precision] Defines the amount of precision to print for a number type
(optional).
[modifier] Overrides the size (type) of the argument (optional).
[type] The type of conversion to be applied (required).
Flags:
Value is left justified (default is right justified). Overrides the 0 flag.
+ Forces the sign (+ or ) to always be shown. Default is to just show the
sign. Overrides the space flag.
space Causes a positive value to display a space for the sign. Negative values
still show the sign.
# Alternate form:
Conversion Character Result
o Precision is increased to make the first digit a zero.
X or x Nonzero value will have 0x or 0X prefixed to it.
E, e, f, g, or G Result will always have a decimal point.
G or g Trailing zeros will not be removed.
0 For d, i, o, u, x, X, e, E, f, g, and G leading zeros are used to pad the
field width instead of spaces. This is useful only with a width specifier.
Precision overrides this flag.
Width:
The width of the field is specified here with a decimal value. If the value is
not large enough to fill the width, then the rest of the field is padded with
spaces (unless the 0 flag is specified). If the value overflows the width of the
field, then the field is expanded to fit the value. If a is used in place of
the width specifer, then the next argument (which must be an int type) specifies
the width of the field. Note: when using the with the width and/or precision
specifier, the width argument comes first, then the precision argument, then the
value to be converted.
Precision:
The precision begins with a dot (.) to distinguish itself from the width
specifier. The precision can be given as a decimal value or as an asterisk ().
If a is used, then the next argument (which is an int type) specifies the
precision. Note: when using the with the width and/or precision specifier, the
width argument comes first, then the precision argument, then the value to be
converted. Precision does not affect the c type.
[.precision] Result
(none) Default precision values:
1 for d, i, o, u, x, X types. The minimum number of digits to appear.
6 for f, e, E types. Specifies the number of digits after the decimal point.
For g or G types all significant digits are shown.
For s type all characters in string are print up to but not including the null
character.
. or .0 For d, i, o, u, x, X types the default precis ion value is used unless
the value is zero in which case no characters are printed.
For f, e, E types no decimal point character or digits are printed.
For g or G types the precision is assumed to be 1.
.n For d, i, o, u, x, X types then at least n digits are printed (padding with
zeros if necessary).
For f, e, E types specifies the number of digits after the decimal point.
For g or G types specifies the number of significant digits to print.
For s type specifies the maximum number of characters to print.
Modifier:
A modifier changes the way a conversion specifier type is interpreted.
[modifier] [type] Effect
h d, i, o, u, x, X Value is first converted to a short int or unsigned short i
nt.
h n Specifies that the pointer points to a short int.
l d, i, o, u, x, X Value is first converted to a long int or unsigned long
int .
l n Specifies that the pointer points to a long int.
L e, E, f, g, G Value is first converted to a long double.
Conversion specifier type:
The conversion specifier specifies what type the argument is to be treated as.
[type] Output
d, i Type signed int.
o Type unsigned int printed in octal.
u Type unsigned int printed in decimal.
x Type unsigned int printed in hexadecimal as dddd using a, b, c, d, e, f.
X Type unsigned int printed in hexadecimal as dddd using A, B, C, D, E, F.
f Type double printed as []ddd.ddd.
e, E Type double printed as []d.ddde�dd where there is one digit printed
before the decimal (zero only if the value is zero). The exponent contains at
least two digits. If type is E then the exponent is printed with a capital E.
g, G Type double printed as type e or E if the exponent is less than 4 or
greater than or equal to the precision. Otherwise printed as type f. Trailing
zeros are removed. Decimal point character appears only if there is a nonzero
decimal digit.
c Type char. Single character is printed.
s Type pointer to array. String is printed according to precision (no precision
prints entire string).
p Prints the value of a pointer (the memory location it holds).
n The argument must be a pointer to an int. Stores the number of characters
printed thus far in the int. No characters are printed.
% A % sign is printed.
The number of characters printed are returned. If an error occurred, 1 is
returned.
2.12.4.2 ..scanf Functions
Declarations:
int fscanf(FILE stream, const char format, ...);
int scanf(const char format, ...);
int sscanf(const char str, const char format, ...);
The ..scanf functions provide a means to input formatted information from a
stream.
fscanf reads formatted input from a stream
scanf reads formatted input from stdin
sscanf reads formatted input from a string
These functions take input in a manner that is specified by the format argument
and store each input field into the following arguments in a left to right
fashion.
Each input field is specified in the format string with a conversion specifier
which specifies how the input is to be stored in the appropriate variable. Other
characters in the format string specify characters that must be matched from the
input, but are not stored in any of the following arguments. If the input does
not match then the function stops scanning and returns. A whitespace character
may match with any whitespace character (space, tab, carriage return, new line,
vertical tab, or formfeed) or the next incompatible character.
An input field is specified with a conversion specifer which begins with the %
character. After the % character come the following in this order:
[] Assignment suppressor (optional).
[width] Defines the maximum number of characters to read (optional).
[modifier] Overrides the size (type) of the argument (optional).
[type] The type of conversion to be applied (required).
Assignment suppressor:
Causes the input field to be scanned but not stored in a variable.
Width:
The maximum width of the field is specified here with a decimal value. If the
input is smaller than the width specifier (i.e. it reaches a nonconvertible
character), then what was read thus far is converted and stored in the variable.
Modifier:
A modifier changes the way a conversion specifier type is interpreted.
[modifier] [type] Effect
h d, i, o, u, x The argument is a short int or unsigned short int.< /td>
h n Specifies that the pointer points to a short int.
l d, i, o, u, x The argument is a long int or unsigned long int .
l n Specifies that the pointer points to a long int.
l e, f, g The argument is a double.
L e, f, g The argument is a long double.
Conversion specifier type:
The conversion specifier specifies what type the argument is. It also controls
what a valid convertible character is (what kind of characters it can read so it
can convert to something compatible).
[type] Input
d Type signed int represented in base 10. Digits 0 through 9 and the sign (+ or
).
i Type signed int. The base (radix) is dependent on the first two characters.
If the first character is a digit from 1 to 9, then it is base 10. If the first
digit is a zero and the second digit is a digit from 1 to 7, then it is base 8
(octal). If the first digit is a zero and the second character is an x or X,
then it is base 16 (hexadecimal).
o Type unsigned int. The input must be in base 8 (octal). Digits 0 through 7
only.
u Type unsigned int. The input must be in base 10 (decimal). Digits 0 through 9
only.
x, X Type unsigned int. The input must be in base 16 (hexadecimal). Digits 0
through 9 or A through Z or a through z. The characters 0x or 0X may be
optionally prefixed to the value.
e, E, f, g, G Type float. Begins with an optional sign. Then one or more
digits, followed by an optional decimalpoint and decimal value. Finally ended
with an optional signed exponent value designated with an e or E.
s Type character array. Inputs a sequence of nonwhitespace characters (space,
tab, carriage return, new line, vertical tab, or formfeed). The array must be
large enough to hold the sequence plus a null character appended to the end.
[...] Type character array. Allows a search set of characters. Allows input of
only those character encapsulated in the brackets (the scanset). If the first
character is a carrot (^), then the scanset is inverted and allows any ASCII
character except those specified between the brackets. On some systems a range
can be specified with the dash character (). By specifying the beginning
character, a dash, and an ending character a range of characters can be included
in the scanset. A null character is appended to the end of the array.
c Type character array. Inputs the number of characters specified in the width
field. If no width field is specified, then 1 is assumed. No null character is
appended to the array.
p Pointer to a pointer. Inputs a memory address in the same fashion of the %p
type produced by the printf function.
n The argument must be a pointer to an int. Stores the number of characters
read thus far in the int. No characters are read from the input stream.
% Requires a matching % sign from the input.
Reading an input field (designated with a conversion specifier) ends when an
incompatible character is met, or the width field is satisfied.
On success the number of input fields converted and stored are returned. If an
input failure occurred, then EOF is returned.
2.12.5 Character I/O Functions
2.12.5.1 fgetc
Declaration:
int fgetc(FILE stream);
Gets the next character (an unsigned char) from the specified stream and
advances the position indicator for the stream.
On success the character is returned. If the endoffile is encountered, then
EOF is returned and the endoffile indicator is set. If an error occurs then
the error indicator for the stream is set and EOF is returned.
2.12.5.2 fgets
Declaration:
char fgets(char str, int n, FILE stream);
Reads a line from the specified stream and stores it into the string pointed to
by str. It stops when either (n1) characters are read, the newline character is
read, or the endoffile is reached, whichever comes first. The newline
character is copied to the string. A null character is appended to the end of
the string.
On success a pointer to the string is returned. On error a null pointer is
returned. If the endoffile occurs before any characters have been read, the
string remains unchanged.
2.12.5.3 fputc
Declaration:
int fputc(int char, FILE stream);
Writes a character (an unsigned char) specified by the argument char to the
specified stream and advances the position indicator for the stream.
On success the character is returned. If an error occurs, the error indicator
for the stream is set and EOF is returned.
2.12.5.4 fputs
Declaration:
int fputs(const char str, FILE stream);
Writes a string to the specified stream up to but not including the null
character.
On success a nonnegative value is returned. On error EOF is returned.
2.12.5.5 getc
Declaration:
int getc(FILE stream);
Gets the next character (an unsigned char) from the specified stream and
advances the position indicator for the stream.
This may be a macro version of fgetc.
On success the character is returned. If the endoffile is encountered, then
EOF is returned and the endoffile indicator is set. If an error occurs then
the error indicator for the stream is set and EOF is returned.
2.12.5.6 getchar
Declaration:
int getchar(void);
Gets a character (an unsigned char) from stdin.
On success the character is returned. If the endoffile is encountered, then
EOF is returned and the endoffile indicator is set. If an error occurs then
the error indicator for the stream is set and EOF is returned.
2.12.5.7 gets
Declaration:
char gets(char str);
Reads a line from stdin and stores it into the string pointed to by str. It
stops when either the newline character is read or when the endoffile is
reached, whichever comes first. The newline character is not copied to the
string. A null character is appended to the end of the string.
On success a pointer to the string is returned. On error a null pointer is
returned. If the endoffile occurs before any characters have been read, the
string remains unchanged.
2.12.5.8 putc
Declaration:
int putc(int char, FILE stream);
Writes a character (an unsigned char) specified by the argument char to the
specified stream and advances the position indicator for the stream.
This may be a macro version of fputc.
On success the character is returned. If an error occurs, the error indicator
for the stream is set and EOF is returned.
2.12.5.9 putchar
Declaration:
int putchar(int char);
Writes a character (an unsigned char) specified by the argument char to stdout.
On success the character is returned. If an error occurs, the error indicator
for the stream is set and EOF is returned.
2.12.5.10 puts
Declaration:
int puts(const char str);
Writes a string to stdout up to but not including the null character. A newline
character is appended to the output.
On success a nonnegative value is returned. On error EOF is returned.
2.12.5.11 ungetc
Declaration:
int ungetc(int char, FILE stream);
Pushes the character char (an unsigned char) onto the specified stream so that
the this is the next character read. The functions fseek, fsetpos, and rewind
discard any characters pushed onto the stream.
Multiple characters pushed onto the stream are read in a FIFO manner (first in,
first out).
On success the character pushed is returned. On error EOF is returned.
2.12.7 Error Functions
2.12.7.1 perror
Declaration:
void perror(const char str);
Prints a descriptive error message to stderr. First the string str is printed
followed by a colon then a space. Then an error message based on the current
setting of the variable errno is printed.
2.13 stdlib.h
The stdlib header defines several general operation functions and macros.
Macros:
NULL
EXIT_FAILURE
EXIT_SUCCESS
RAND_MAX
MB_CUR_MAX
Variables:
typedef size_t
typedef wchar_t
struct div_t
struct ldiv_t
Functions:
abort();
abs();
atexit();
atof();
atoi();
atol();
bsearch();
calloc();
div();
exit();
free();
getenv();
labs();
ldiv();
malloc();
mblen();
mbstowcs();
mbtowc();
qsort();
rand();
realloc();
srand();
strtod();
strtol();
strtoul();
system();
wcstombs();
wctomb();
2.13.1 Variables and Definitions
size_t is the unsigned integer result of the sizeof keyword.
wchar_t is an integer type of the size of a wide character constant.
div_t is the structure returned by the div function.
ldiv_t is the structure returned by the ldiv function.
NULL is the value of a null pointer constant.
EXIT_FAILURE and EXIT_SUCCESS are values for the exit function to return
termination status.
RAND_MAX is the maximum value returned by the rand function.
MB_CUR_MAX is the maximum number of bytes in a multibyte character set which
cannot be larger than MB_LEN_MAX.
2.13.2 String Functions
2.13.2.1 atof
Declaration:
double atof(const char str);
The string pointed to by the argument str is converted to a floatingpoint
number (type double). Any initial whitespace characters are skipped (space, tab,
carriage return, new line, vertical tab, or formfeed). The number may consist of
an optional sign, a string of digits with an optional decimal character, and an
optional e or E followed by a optionally signed exponent. Conversion stops when
the first unrecognized character is reached.
On success the converted number is returned. If no conversion can be made, zero
is returned. If the value is out of range of the type double, then HUGE_VAL is
returned with the appropriate sign and ERANGE is stored in the variable errno.
If the value is too small to be returned in the type double, then zero is
returned and ERANGE is stored in the variable errno.
2.13.2.2 atoi
Declaration:
int atoi(const char str);
The string pointed to by the argument str is converted to an integer (type int).
Any initial whitespace characters are skipped (space, tab, carriage return, new
line, vertical tab, or formfeed). The number may consist of an optional sign and
a string of digits. Conversion stops when the first unrecognized character is
reached.
On success the converted number is returned. If the number cannot be converted,
then 0 is returned.
2.13.2.3 atol
Declaration:
long int atol(const char str);
The string pointed to by the argument str is converted to a long integer (type
long int). Any initial whitespace characters are skipped (space, tab, carriage
return, new line, vertical tab, or formfeed). The number may consist of an
optional sign and a string of digits. Conversion stops when the first
unrecognized character is reached.
On success the converted number is returned. If the number cannot be converted,
then 0 is returned.
2.13.2.4 strtod
Declaration:
double strtod(const char str, char endptr);
The string pointed to by the argument str is converted to a floatingpoint
number (type double). Any initial whitespace characters are skipped (space, tab,
carriage return, new line, vertical tab, or formfeed). The number may consist of
an optional sign, a string of digits with an optional decimal character, and an
optional e or E followed by a optionally signed exponent. Conversion stops when
the first unrecognized character is reached.
The argument endptr is a pointer to a pointer. The address of the character that
stopped the scan is stored in the pointer that endptr points to.
On success the converted number is returned. If no conversion can be made, zero
is returned. If the value is out of range of the type double, then HUGE_VAL is
returned with the appropriate sign and ERANGE is stored in the variable errno.
If the value is too small to be returned in the type double, then zero is
returned and ERANGE is stored in the variable errno.
2.13.2.5 strtol
Declaration:
long int strtol(const char str, char endptr, int base);
The string pointed to by the argument str is converted to a long integer (type
long int). Any initial whitespace characters are skipped (space, tab, carriage
return, new line, vertical tab, or formfeed). The number may consist of an
optional sign and a string of digits. Conversion stops when the first
unrecognized character is reached.
If the base (radix) argument is zero, then the conversion is dependent on the
first two characters. If the first character is a digit from 1 to 9, then it is
base 10. If the first digit is a zero and the second digit is a digit from 1 to
7, then it is base 8 (octal). If the first digit is a zero and the second
character is an x or X, then it is base 16 (hexadecimal).
If the base argument is from 2 to 36, then that base (radix) is used and any
characters that fall outside of that base definition are considered
unconvertible. For base 11 to 36, the characters A to Z (or a to z) are used. If
the base is 16, then the characters 0x or 0X may precede the number.
The argument endptr is a pointer to a pointer. The address of the character that
stopped the scan is stored in the pointer that endptr points to.
On success the converted number is returned. If no conversion can be made, zero
is returned. If the value is out of the range of the type long int, then
LONG_MAX or LONG_MIN is returned with the sign of the correct value and ERANGE
is stored in the variable errno.
2.13.2.6 strtoul
Declaration:
unsigned long int strtoul(const char str, char endptr, int base);
The string pointed to by the argument str is converted to an unsigned long
integer (type unsigned long int). Any initial whitespace characters are skipped
(space, tab, carriage return, new line, vertical tab, or formfeed). The number
may consist of an optional sign and a string of digits. Conversion stops when
the first unrecognized character is reached.
If the base (radix) argument is zero, then the conversion is dependent on the
first two characters. If the first character is a digit from 1 to 9, then it is
base 10. If the first digit is a zero and the second digit is a digit from 1 to
7, then it is base 8 (octal). If the first digit is a zero and the second
character is an x or X, then it is base 16 (hexadecimal).
If the base argument is from 2 to 36, then that base (radix) is used and any
characters that fall outside of that base definition are considered
unconvertible. For base 11 to 36, the characters A to Z (or a to z) are used. If
the base is 16, then the characters 0x or 0X may precede the number.
The argument endptr is a pointer to a pointer. The address of the character that
stopped the scan is stored in the pointer that endptr points to.
On success the converted number is returned. If no conversion can be made, zero
is returned. If the value is out of the range of the type unsigned long int,
then ULONG_MAX is returned and ERANGE is stored in the variable errno.
2.13.3 Memory Functions
2.13.3.1 calloc
Declaration:
void calloc(size_t nitems, size_t size);
Allocates the requested memory and returns a pointer to it. The requested size
is nitems each size bytes long (total memory requested is nitemssize). The
space is initialized to all zero bits.
On success a pointer to the requested space is returned. On failure a null
pointer is returned.
2.13.3.2 free
Declaration:
void free(void ptr);
Deallocates the memory previously allocated by a call to calloc, malloc, or
realloc. The argument ptr points to the space that was previously allocated. If
ptr points to a memory block that was not allocated with calloc, malloc, or
realloc, or is a space that has been deallocated, then the result is undefined.
No value is returned.
2.13.3.3 malloc
Declaration:
void malloc(size_t size);
Allocates the requested memory and returns a pointer to it. The requested size
is size bytes. The value of the space is indeterminate.
On success a pointer to the requested space is returned. On failure a null
pointer is returned.
2.13.3.4 realloc
Declaration:
void realloc(void ptr, size_t size);
Attempts to resize the memory block pointed to by ptr that was previously
allocated with a call to malloc or calloc. The contents pointed to by ptr are
unchanged. If the value of size is greater than the previous size of the block,
then the additional bytes have an undeterminate value. If the value of size is
less than the previous size of the block, then the difference of bytes at the
end of the block are freed. If ptr is null, then it behaves like malloc. If ptr
points to a memory block that was not allocated with calloc or malloc, or is a
space that has been deallocated, then the result is undefined. If the new space
cannot be allocated, then the contents pointed to by ptr are unchanged. If size
is zero, then the memory block is completely freed.
On success a pointer to the memory block is returned (which may be in a
different location as before). On failure or if size is zero, a null pointer is
returned.
2.13.4 Environment Functions
2.13.4.1 abort
Declaration:
void abort(void);
Causes an abnormal program termination. Raises the SIGABRT signal and an
unsuccessful termination status is returned to the environment. Whether or not
open streams are closed is implementationdefined.
No return is possible.
2.13.4.2 atexit
Declaration:
int atexit(void (func)(void));
Causes the specified function to be called when the program terminates normally.
At least 32 functions can be registered to be called when the program
terminates. They are called in a lastin, firstout basis (the last function
registered is called first).
On success zero is returned. On failure a nonzero value is returned.
2.13.4.3 exit
Declaration:
void exit(int status);
Causes the program to terminate normally. First the functions registered by
atexit are called, then all open streams are flushed and closed, and all
temporary files opened with tmpfile are removed. The value of status is returned
to the environment. If status is EXIT_SUCCESS, then this signifies a successful
termination. If status is EXIT_FAILURE, then this signifies an unsuccessful
termination. All other values are implementationdefined.
No return is possible.
2.13.4.4 getenv
Declaration:
char getenv(const char name);
Searches for the environment string pointed to by name and returns the
associated value to the string. This returned value should not be written to.
If the string is found, then a pointer to the string's associated value is
returned. If the string is not found, then a null pointer is returned.
2.13.4.5 system
Declaration:
int system(const char string);
The command specified by string is passed to the host environment to be executed
by the command processor. A null pointer can be used to inquire whether or not
the command processor exists.
If string is a null pointer and the command processor exists, then zero is
returned. All other return values are implementationdefined.
2.13.5 Searching and Sorting Functions
2.13.5.1 bsearch
Declaration:
void bsearch(const void key, const void base, size_t nitems, size_t size, int
(compar)(const void , const void ));
Performs a binary search. The beginning of the array is pointed to by base. It
searches for an element equal to that pointed to by key. The array is nitems
long with each element in the array size bytes long.
The method of comparing is specified by the compar function. This function takes
two arguments, the first is the key pointer and the second is the current
element in the array being compared. This function must return less than zero if
the compared value is less than the specified key. It must return zero if the
compared value is equal to the specified key. It must return greater than zero
if the compared value is greater than the specified key.
The array must be arranged so that elements that compare less than key are
first, elements that equal key are next, and elements that are greater than key
are last.
If a match is found, a pointer to this match is returned. Otherwise a null
pointer is returned. If multiple matching keys are found, which key is returned
is unspecified.
2.13.5.2 qsort
Declaration:
void qsort(void base, size_t nitems, size_t size, int (compar)(const void ,
const void));
Sorts an array. The beginning of the array is pointed to by base. The array is
nitems long with each element in the array size bytes long.
The elements are sorted in ascending order according to the compar function.
This function takes two arguments. These arguments are two elements being
compared. This function must return less than zero if the first argument is less
than the second. It must return zero if the first argument is equal to the
second. It must return greater than zero if the first argument is greater than
the second.
If multiple elements are equal, the order they are sorted in the array is
unspecified.
No value is returned.
Example:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
char string_array[10][50]={"John",
"Jane",
"Mary",
"Rogery",
"Dave",
"Paul",
"Beavis",
"Astro",
"George",
"Elroy"};
/* Sort the list */
qsort(string_array,10,50,strcmp);
/* Search for the item "Elroy" and print it */
printf("%s",bsearch("Elroy",string_array,10,50,strcmp));
return 0;
}
2.13.6 Math Functions
2.13.6.1 abs
Declaration:
int abs(int x);
Returns the absolute value of x. Note that in two's compliment that the most
maximum number cannot be represented as a positive number. The result in this
case is undefined.
The absolute value is returned.
2.13.6.2 div
Declaration:
div_t div(int numer, int denom);
Divides numer (numerator) by denom (denominator). The result is stored in the
structure div_t which has two members:
int qout;
int rem;
Where quot is the quotient and rem is the remainder. In the case of inexact
division, quot is rounded down to the nearest integer. The value numer is equal
to quot denom + rem.
The value of the division is returned in the structure.
2.13.6.3 labs
Declaration:
long int labs(long int x);
Returns the absolute value of x. Not that in two's compliment that the most
maximum number cannot be represented as a positive number. The result in this
case is undefined.
The absolute value is returned.
2.13.6.4 ldiv
Declaration:
ldiv_t ldiv(long int numer, long int denom);
Divides numer (numerator) by denom (denominator). The result is stored in the
structure ldiv_t which has two members:
long int qout;
long int rem;
Where quot is the quotient and rem is the remainder. In the case of inexact
division, quot is rounded down to the nearest integer. The value numer is equal
to quot denom + rem.
The value of the division is returned in the structure.
2.13.6.5 rand
Declaration:
int rand(void);
Returns a pseudorandom number in the range of 0 to RAND_MAX.
The random number is returned.
2.13.6.6 srand
Declaration:
void srand(unsigned int seed);
This function seeds the random number generator used by the function rand.
Seeding srand with the same seed will cause rand to return the same sequence of
pseudorandom numbers. If srand is not called, rand acts as if srand(1) has been
called.
No value is returned.
2.13.7 Multibyte Functions
The behavior of the multibyte functions are affected by the setting of LC_CTYPE
in the location settings.
2.13.7.1 mblen
Declaration:
int mblen(const char str, size_t n);
Returns the length of a multibyte character pointed to by the argument str. At
most n bytes will be examined.
If str is a null pointer, then zero is returned if multibyte characters are not
statedependent (shift state). Otherwise a nonzero value is returned if
multibyte character are statedependent.
If str is not null, then the number of bytes that are contained in the multibyte
character pointed to by str are returned. Zero is returned if str points to a
null character. A value of 1 is returned if str does not point to a valid
multibyte character.
2.13.7.2 mbstowcs
Declaration:
size_t mbstowcs(schar_t pwcs, const char str, size_t n);
Converts the string of multibyte characters pointed to by the argument str to
the array pointed to by pwcs. It stores no more than n values into the array.
Conversion stops when it reaches the null character or n values have been
stored. The null character is stored in the array as zero but is not counted in
the return value.
If an invalid multibyte character is reached, then the value 1 is returned.
Otherwise the number of values stored in the array is returned not including the
terminating zero character.
2.13.7.3 mbtowc
Declaration:
int mbtowc(whcar_t pwc, const char str, size_t n);
Examines the multibyte character pointed to by the argument str. The value is
converted and stored in the argument pwc if pwc is not null. It scans at most n
bytes.
If str is a null pointer, then zero is returned if multibyte characters are not
statedependent (shift state). Otherwise a nonzero value is returned if
multibyte character are statedependent.
If str is not null, then the number of bytes that are contained in the multibyte
character pointed to by str are returned. Zero is returned if str points to a
null character. A value of 1 is returned if str does not point to a valid
multibyte character.
2.13.7.4 wcstombs
Declaration:
size_t wcstombs(char str, const wchar_t pwcs, size_t n);
Converts the codes stored in the array pwcs to multibyte characters and stores
them in the string str. It copies at most n bytes to the string. If a multibyte
character overflows the n constriction, then none of that multibyte character's
bytes are copied. Conversion stops when it reaches the null character or n bytes
have been written to the string. The null character is stored in the string, but
is not counted in the return value.
If an invalid code is reached, the value 1 is returned. Otherwise the number of
bytes stored in the string is returned not including the terminating null
character.
2.13.7.5 wctomb
Declaration:
int wctomb(char str, wchar_t wchar);
Examines the code which corresponds to a multibyte character given by the
argument wchar. The code is converted to a multibyte character and stored into
the string pointed to by the argument str if str is not null.
If str is a null pointer, then zero is returned if multibyte characters are not
statedependent (shift state). Otherwise a nonzero value is returned if
multibyte character are statedependent.
If str is not null, then the number of bytes that are contained in the multibyte
character wchar are returned. A value of 1 is returned if wchar is not a valid
multibyte character
string.h
The string header provides many functions useful for manipulating strings
(character arrays).
Macros:
NULL
Variables:
typedef size_t
Functions:
memchr();
memcmp();
memcpy();
memmove();
memset();
strcat();
strncat();
strchr();
strcmp();
strncmp();
strcoll();
strcpy();
strncpy();
strcspn();
strerror();
strlen();
strpbrk();
strrchr();
strspn();
strstr();
strtok();
strxfrm();
2.14.1 Variables and Definitions
size_t is the unsigned integer result of the sizeof keyword.
NULL is the value of a null pointer constant.
2.14.2 memchr
Declaration:
void memchr(const void str, int c, size_t n);
Searches for the first occurrence of the character c (an unsigned char) in the
first n bytes of the string pointed to by the argument str.
Returns a pointer pointing to the first matching character, or null if no match
was found.
2.14.3 memcmp
Declaration:
int memcmp(const void str1, const void str2, size_t n);
Compares the first n bytes of str1 and str2. Does not stop comparing even after
the null character (it always checks n characters).
Returns zero if the first n bytes of str1 and str2 are equal. Returns less than
zero or greater than zero if str1 is less than or greater than str2
respectively.
2.14.4 memcpy
Declaration:
void memcpy(void str1, const void str2, size_t n);
Copies n characters from str2 to str1. If str1 and str2 overlap the behavior is
undefined.
Returns the argument str1.
2.14.5 memmove
Declaration:
void memmove(void str1, const void str2, size_t n);
Copies n characters from str2 to str1. If str1 and str2 overlap the information
is first completely read from str1 and then written to str2 so that the
characters are copied correctly.
Returns the argument str1.
2.14.6 memset
Declaration:
void memset(void str, int c, size_t n);
Copies the character c (an unsigned char) to the first n characters of the
string pointed to by the argument str.
The argument str is returned.
2.14.7 strcat
Declaration:
char strcat(char str1, const char str2);
Appends the string pointed to by str2 to the end of the string pointed to by
str1. The terminating null character of str1 is overwritten. Copying stops once
the terminating null character of str2 is copied. If overlapping occurs, the
result is undefined.
The argument str1 is returned.
2.14.8 strncat
Declaration:
char strncat(char str1, const char str2, size_t n);
Appends the string pointed to by str2 to the end of the string pointed to by
str1 up to n characters long. The terminating null character of str1 is
overwritten. Copying stops once n characters are copied or the terminating null
character of str2 is copied. A terminating null character is always appended to
str1. If overlapping occurs, the result is undefined.
The argument str1 is returned.
2.14.9 strchr
Declaration:
char strchr(const char str, int c);
Searches for the first occurrence of the character c (an unsigned char) in the
string pointed to by the argument str. The terminating null character is
considered to be part of the string.
Returns a pointer pointing to the first matching character, or null if no match
was found.
2.14.10 strcmp
Declaration:
int strcmp(const char str1, const char str2);
Compares the string pointed to by str1 to the string pointed to by str2.
Returns zero if str1 and str2 are equal. Returns less than zero or greater than
zero if str1 is less than or greater than str2 respectively.
2.14.11 strncmp
Declaration:
int strncmp(const char str1, const char str2, size_t n);
Compares at most the first n bytes of str1 and str2. Stops comparing after the
null character.
Returns zero if the first n bytes (or null terminated length) of str1 and str2
are equal. Returns less than zero or greater than zero if str1 is less than or
greater than str2 respectively.
2.14.12 strcoll
Declaration:
int strcoll(const char str1, const char str2);
Compares string str1 to str2. The result is dependent on the LC_COLLATE setting
of the location.
Returns zero if str1 and str2 are equal. Returns less than zero or greater than
zero if str1 is less than or greater than str2 respectively.
2.14.13 strcpy
Declaration:
char strcpy(char str1, const char str2);
Copies the string pointed to by str2 to str1. Copies up to and including the
null character of str2. If str1 and str2 overlap the behavior is undefined.
Returns the argument str1.
2.14.14 strncpy
Declaration:
char strncpy(char str1, const char str2, size_t n);
Copies up to n characters from the string pointed to by str2 to str1. Copying
stops when n characters are copied or the terminating null character in str2 is
reached. If the null character is reached, the null characters are continually
copied to str1 until n characters have been copied.
Returns the argument str1.
2.14.15 strcspn
Declaration:
size_t strcspn(const char str1, const char str2);
Finds the first sequence of characters in the string str1 that does not contain
any character specified in str2.
Returns the length of this first sequence of characters found that do not match
with str2.
2.14.16 strerror
Declaration:
char strerror(int errnum);
Searches an internal array for the error number errnum and returns a pointer to
an error message string.
Returns a pointer to an error message string.
2.14.17 strlen
Declaration:
size_t strlen(const char str);
Computes the length of the string str up to but not including the terminating
null character.
Returns the number of characters in the string.
2.14.18 strpbrk
Declaration:
char strpbrk(const char str1, const char str2);
Finds the first character in the string str1 that matches any character
specified in str2.
A pointer to the location of this character is returned. A null pointer is
returned if no character in str2 exists in str1.
Example:
#include <string.h>
#include <stdio.h>
main()
{
char string[] = "Hi there, Chip!";
char string_ptr;
while ((string_ptr = strpbrk(string, " ")) != NULL)
string_ptr = '';
printf("New string is \"%s\".\n", string);
}
The output should result in every space in the string being converted to a dash
().
2.14.19 strrchr
Declaration:
char strrchr(const char str, int c);
Searches for the last occurrence of the character c (an unsigned char) in the
string pointed to by the argument str. The terminating null character is
considered to be part of the string.
Returns a pointer pointing to the last matching character, or null if no match
was found.
2.14.20 strspn
Declaration:
size_t strspn(const char str1, const char str2);
Finds the first sequence of characters in the string str1 that contains any
character specified in str2.
Returns the length of this first sequence of characters found that match with
str2.
Example:
#include<string.h>
#include<stdio.h>
main()
{
char string[] = "7803 Elm St.";
printf("The number length is %d.\n", strspn(string, "1234567890"));
}
The output should be: The number length is 4.
2.14.21 strstr
Declaration:
char strstr(const char str1, const char str2);
Finds the first occurrence of the entire string str2 (not including the
terminating null character) which appears in the string str1.
Returns a pointer to the first occurrence of str2 in str1. If no match was
found, then a null pointer is returned. If str2 points to a string of zero
length, then the argument str1 is returned.
2.14.22 strtok
Declaration:
char strtok(char str1, const char str2);
Breaks string str1 into a series of tokens. If str1 and str2 are not null, then
the following search sequence begins. The first character in str1 that does not
occur in str2 is found. If str1 consists entirely of characters specified in
str2, then no tokens exist and a null pointer is returned. If this character is
found, then this marks the beginning of the first token. It then begins
searching for the next character after that which is contained in str2. If this
character is not found, then the current token extends to the end of str1. If
the character is found, then it is overwritten by a null character, which
terminates the current token. The function then saves the following position
internally and returns.
Subsequent calls with a null pointer for str1 will cause the previous position
saved to be restored and begins searching from that point. Subsequent calls may
use a different value for str2 each time.
Returns a pointer to the first token in str1. If no token is found then a null
pointer is returned.
Example:
#include<string.h>
#include<stdio.h>
main()
{
char search_string[] = "Woody Norm Cliff";
char array[50];
int loop;
array[0] = strtok(search_string," ");
if (array[0]==NULL)
{
printf("No test to search.\n");
exit(0);
}
for (loop = 1; loop < 50; loop++)
{
array[loop] = strtok(NULL, " ");
if (array[loop] == NULL)
break;
}
for (loop = 0; loop < 50; loop++)
{
If (array[loop] == NULL)
break;
printf("Item #%d is %s.\n", loop, array[loop]);
}
}
This program replaces each space into a null character and stores a pointer to
each substring into the array. It then prints out each item.
2.14.23 strxfrm
Declaration:
size_t strxfrm(char str1, const char str2, size_t n);
Transforms the string str2 and places the result into str1. It copies at most n
characters into str1 including the null terminating character. The
transformation occurs such that strcmp applied to two separate converted strings
returns the same value as strcoll applied to the same two strings. If
overlapping occurs, the result is undefined.
Returns the length of the transformed string (not including the null character).
time.h
The time header provides several functions useful for reading and converting the
current time and date. Some functions behavior is defined by the LC_TIME
category of the location setting.
Macros:
NULL
CLOCKS_PER_SEC
Variables:
typedef size_t
typedef clock_t
typedef size_t
struct tm
Functions:
asctime();
clock();
ctime();
difftime();
gmtime();
localtime();
mktime();
strftime();
time();
2.15.1 Variables and Definitions
NULL is the value of a null pointer constant.
CLOCKS_PER_SEC is the number of processor clocks per second.
size_t is the unsigned integer result of the sizeof keyword.
clock_t is a type suitable for storing the processor time.
time_t is a type suitable for storing the calendar time.
struct tm is a structure used to hold the time and date. Its members are as
follows:
int tm_sec; /* seconds after the minute (0 to 61) */
int tm_min; /* minutes after the hour (0 to 59) */
int tm_hour; /* hours since midnight (0 to 23) */
int tm_mday; /* day of the month (1 to 31) */
int tm_mon; /* months since January (0 to 11) */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday (0 to 6 Sunday=0) */
int tm_yday; /* days since January 1 (0 to 365) */
int tm_isdst; /* Daylight Savings Time */
If tm_isdst is zero, then Daylight Savings Time is not in effect. If it is a
positive value, then Daylight Savings Time is in effect. If it is negative, then
the function using it is requested to attempt to calculate whether or not
Daylight Savings Time is in effect for the given time.
Note that tm_sec may go as high as 61 to allow for up to two leap seconds.
2.15.2 asctime
Declaration:
char asctime(const struct tm timeptr);
Returns a pointer to a string which represents the day and time of the structure
timeptr. The string is in the following format:
DDD MMM dd hh:mm:ss YYYY
DDD Day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat)
MMM Month of the year (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov,
Dec)
dd Day of the month (1,...,31)
hh Hour (0,...,23)
mm Minute (0,...,59)
ss Second (0,...,59)
YYYY Year
The string is terminated with a newline character and a null character. The
string is always 26 characters long (including the terminating newline and null
characters).
A pointer to the string is returned.
Example:
#include<time.h>
#include<stdio.h>
int main(void)
{
time_t timer;
timer=time(NULL);
printf("The current time is %s.\n",asctime(localtime(&timer)));
return 0;
}
2.15.3 clock
Declaration:
clock_t clock(void);
Returns the processor clock time used since the beginning of an implementation
defined era (normally the beginning of the program). The returned value divided
by CLOCKS_PER_SEC results in the number of seconds. If the value is unavailable,
then 1 is returned.
Example:
#include<time.h>
#include<stdio.h>
int main(void)
{
clock_t ticks1, ticks2;
ticks1=clock();
ticks2=ticks1;
while((ticks2/CLOCKS_PER_SECticks1/CLOCKS_PER_SEC)<1)
ticks2=clock();
printf("Took %ld ticks to wait one second.\n",ticks2ticks1);
printf("This value should be the same as CLOCKS_PER_SEC which is
%ld.\n",CLOCKS_PER_SEC);
return 0;
}
2.15.4 ctime
Declaration:
char ctime(const time_t timer);
Returns a string representing the localtime based on the argument timer. This is
equivalent to:
asctime(locatime(timer));
The returned string is in the following format:
DDD MMM dd hh:mm:ss YYYY
DDD Day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat)
MMM Month of the year (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov,
Dec)
dd Day of the month (1,...,31)
hh Hour (0,...,23)
mm Minute (0,...,59)
ss Second (0,...,59)
YYYY Year
The string is terminated with a newline character and a null character. The
string is always 26 characters long (including the terminating newline and null
characters).
A pointer to the string is returned.
2.15.5 difftime
Declaration:
double difftime(time_t time1, time_t time2);
Calculates the difference of seconds between time1 and time2 (time1time2).
Returns the number of seconds.
2.15.6 gmtime
Declaration:
struct tm gmtime(const time_t timer);
The value of timer is broken up into the structure tm and expressed in
Coordinated Universal Time (UTC) also known as Greenwich Mean Time (GMT).
A pointer to the structure is returned. A null pointer is returned if UTC is not
available.
2.15.7 localtime
Declaration:
struct tm localtime(const time_t timer);
The value of timer is broken up into the structure tm and expressed in the local
time zone.
A pointer to the structure is returned.
Example:
#include<time.h>
#include<stdio.h>
int main(void)
{
time_t timer;
timer=time(NULL);
printf("The current time is %s.\n",asctime(localtime(&timer)));
return 0;
}
2.15.8 mktime
Declaration:
time_t mktime(struct tm timeptr);
Converts the structure pointed to by timeptr into a time_t value according to
the local time zone. The values in the structure are not limited to their
constraints. If they exceed their bounds, then they are adjusted accordingly so
that they fit within their bounds. The original values of tm_wday (day of the
week) and tm_yday (day of the year) are ignored, but are set correctly after the
other values have been constrained. tm_mday (day of the month) is not corrected
until after tm_mon and tm_year are corrected.
After adjustment the structure still represents the same time.
The encoded time_t value is returned. If the calendar time cannot be
represented, then 1 is returned.
Example:
#include<time.h>
#include<stdio.h>
/* find out what day of the week is January 1, 2001
(first day of the 21st century) */
int main(void)
{
struct tm time_struct;
char days[7][4]={"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_struct.tm_year=20011900;
time_struct.tm_mon=0;
time_struct.tm_mday=1;
time_struct.tm_sec=0;
time_struct.tm_min=0;
time_struct.tm_hour=0;
time_struct.tm_isdst=1;
if(mktime(&time_struct)==1)
{
printf("Error getting time.\n");
exit(0);
}
printf("January 1, 2001 is a %s.\n",days[time_struct.tm_wday]);
return 0;
}
2.15.9 strftime
Declaration:
size_t strftime(char str, size_t maxsize, const char format, const struct tm
timeptr);
Formats the time represented in the structure timeptr according to the
formatting rules defined in format and stored into str. No more than maxsize
characters are stored into str (including the terminating null character).
All characters in the format string are copied to the str string, including the
terminating null character, except for conversion characters. A conversion
character begins with the % sign and is followed by another character which
defines a special value that it is to be replaced by.
Conversion
Character What it is replaced by
%a abbreviated weekday name
%A full weekday name
%b abbreviated month name
%B full month name
%c appropriate date and time representation
%d day of the month (0131)
%H hour of the day (0023)
%I hour of the day (0112)
%j day of the year (001366)
%m month of the year (0112)
%M minute of the hour (0059)
%p AM/PM designator
%S second of the minute (0061)
%U week number of the year where Sunday is the first day of week 1 (0053)
%w weekday where Sunday is day 0 (06)
%W week number of the year where Monday is the first day of week 1 (0053)
%x appropriate date representation
%X appropriate time representation
%y year without century (0099)
%Y year with century
%Z time zone (possibly abbreviated) or no characters if time zone isunavailable
%% %
Returns the number of characters stored into str not including the terminating
null character. On error zero is returned.
time
Declaration:
time_t time(time_t timer);
Calculates the current calender time and encodes it into time_t format.
The time_t value is returned. If timer is not a null pointer, then the value is
also stored into the object it points to. If the time is unavailable, then 1 is
returned.
Number Constants
use 0 (zero) before octal literals and 0x for hex, eg 023 = 19, 0x23 = 35
use e or E for scientific notation eg 3.1e2 = 310, 3.1e2 = 0.031
floats are held as doubles, so use f or F after number to hold as a float
use l or L after for long doubles
Character Constants
Escape sequences (using backslashes)
all single characters stored as ints representing their ASCII/EBCIDIC code
stored as octal '\123' (or 'x23' for hex)
\" "
\' '
\? ?
\\ \
\a BEL (bell)
\b BS (backspace)
\f FF (form feed)
\r CR (carriage return)
\n NL (newline = "\r\f")
\t HT (horizontal tab)
\v VT (vertical tab)
Formatting output (int w = 12; float x = 12.34, char y = "A", z = "Hello")
short/long (int) %d
double for double precision floatingpoint number %f
floats
minimum total field width (including decimal point).precision
(12.34) printf("(%f)", x);
( 12.34) printf("(%7f)", x);
(12.3) printf("(.1f)", x);
(12) printf("(%.0f)", x);
(12) printf("(%d)", x);
(12.3 ) printf("(%4f)", x);
(12.340) printf("(%6.3f)", x);
ints
(12) printf("(%d)", w); equivalent to ".0f" or "%i"
( 12) printf("(4d)", w);
chars
(Hello) printf("(%s)", z);
(A) printf("(%c)", y);
(%) printf("%%");
can use, eg %10d for leftjustification with minimum field width
unsigned ints or chars are always >= 0
puts("Hello\n");
is the same as
printf("Hello\n");
used for string constants (without variables)
char c;
c = getchar();
makes c equal to the next character typed
putchar('a');
putchar('\n');
putchar(c);
displays character c on screen (c/w puts)
be careful when getchar follows scanf getchar will hold '\n' at end of scanf
#include <string.h>
char strcat(char s1, const char s2);
/* appends s2 to s1, overwrites s1's '\0', s1[0] returned */
char strchr(const char s, int c);
/* return c if c is in s[], otherwise NULL */
char strcpy(char s1, const char s2);
/* copies s2 to s1, s1[0] returned */
size_t strlen(const char s);
/* length of s[], not including '\0' */
char strncpy(char s1, const char s2, size_t n);
/* copies 1st n characters of s2 to s1, s1[0] returned */
PreANSI C
K&R C
void f(i, c)
int i, char c;
{
/* ... */
}
argument types just below )
char f(i)
int i;
{
/* ... */
}
instead of
char f(int i)
{
/* ... */
}
cannot use
void
so use
char
instead
C Standard Library
<assert.h>
<ctype.h>
<errno.h>
<math.h>
<stdarg.h>
<stdio.h>
FILE fopen(const char filename, const char access_mode);
Access mode
r Opens file for read operations only. Fails if the file does not exist
w Opens a new file for writing. If the file exists, its contents are destroyed
a Opens file for appending. A new file is created if the file does not exist
r+ Opens an existing file for both read and write operations. Error is returned
if file does not exist
w+ Creates a file and opens it for both reading and writing. If file exists,
current contents are destroyed
a+ Opens file for reading and appending. Creates a new file if one does not
exist
FILE infile = fopen(“c:/input.dat”, “r+”);
int fclose(FILE file_pointer);
If the file is successfully closed, fclose returns a zero
In case of an error, the return value = the constant EOF defined in stdio.h
<stdlib.h>
<string.h>
<time.h>
<complex.h>
Microsoft Extensions
<dos.h>
<io.h>
int access(char path , int mode);
Checks whether a file exists and whether read/write operations are permitted
Mode Interpretation
00 Only existence of file will be checked
02 Check if file has write permission
04 Check if file has read permission
06 Check if file has read and write permission
Returns 0 if true, 1 if not
int chmod(char path, int pmode );
alters the read/write permission settings of a file
S_IWRITE Both reading and writing permitted
S_IREAD Only reading permitted
S_IREAD | S_IWRITE Both reading and writing permitted
Windows Programming
/* winhello1.c */
#include <windows.h>
int WINAPI WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow)
{
MessageBox (NULL, TEXT ("Hello"), TEXT ("Hello"), 0);
return 0;
}
/* winhello2.c */
#include <windows.h>
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain (HINSTANCE hInstance,
HINSTANCE hPrevInstance,
PSTR szCmdLine,
int iCmdShow)
{
static TCHAR szAppName[] = TEXT ("HelloWin");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("This program requires Windows NT!"),
szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow (szAppName, // window class name
TEXT ("The Hello Program"), // window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT, // initial x size
CW_USEDEFAULT, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL); // creation parameters
ShowWindow (hwnd, iCmdShow);
UpdateWindow (hwnd);
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
RECT rect;
switch (message)
{
case WM_CREATE:
PlaySound (TEXT ("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC);
return 0;
case WM_PAINT:
hdc = BeginPaint (hwnd, &ps);
GetClientRect (hwnd, &rect);
DrawText (hdc, TEXT ("Hello, Windows 98!"), 1, &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint (hwnd, &ps);
return 0;
case WM_DESTROY:
PostQuitMessage (0);
return 0;
}
return DefWindowProc (hwnd, message, wParam, lParam);
}
abort() Abort Process and Return Error
abs() Calculate Absolute Value of Integer
access() Check File Permission Setting
acos() Calculate ArcCosine
acosl() Calculate Long Double ArcCosine
asctime() Converts Time from Structure to String
asin() Calculate Arcsine
asinl() Calculate Long Double ArcSine
assert() Diagnostic Message Generator
atan() Calculate Arctangent
atanl() Calculate Long Double ArcTangent
atan2() Calculate Arctangent of y/x
atan2l() Calculate Long Double ArcTangent of y/x
atof() Convert String to Double
atexit() Register Terminating Function
atoi() Convert String to Integer
atol() Convert String to Long
_atold() Convert String to Long Double
_beginthread() Create a Thread (OS/2)
bessel() Return Result of a Bessel Function of x
bsearch() Performs Binary Search
cabs() Calculate Absolute Value of Complex Number
cabsl() Calculate Long Double Abs Value of a Complex Number
ceil() Calculate Ceiling of Value
ceill() Calculate Long Double Ceiling Value
_cexit() Perform Exit Procedures Without Exiting
_c_exit() Perform _exit Procedures Without Exiting
cgets() Get a Character String From the Console
_chain_intr() Chain Interrupt Handlers
chdir() Change Current Working Directory
_chdrive() Change Current Drive
chmod() Change File Permission Setting
chsize() Change Size of File
_clear87() Get and Clear 8087/80287 Status Word
clearerr() Clear Error Indicator for a Stream
clock() Returns elapsed CPU time
close() Close File
_control87() Get and Set 8087/80287 Status Word
cos() Calculate Cosine
cosh() Calculate Hyperbolic Cosine
coshl() Calculate Long Double Hyperbolic Cosine
cosl() Calculate Long Double Cosine
cprintf() Formatted Write to Console
cputs() Write a String to the Console
creat() Create a New File
cscanf() Read Formatted Data from Console
ctime() Convert Time from Long Integer to String
cwait() Suspend calling process until child terminates
dieeetomsbin() Convert IEEE Double to MS Binary Double
dmsbintoieee() Convert Double MS Binary to IEEE Double
difftime() Find the Difference between Two Times
_disable() Disable interrupts
div() Divides integers
dup() Create Second Handle for Open File
dup2() Reassign a File Handle
ecvt() Convert Double to String
_enable() Enables interrupts
_endthread() End a Thread (OS/2)
eof() Test for End of File
exec...() An Overview of the Eight Exec Functions
execl() Execute Program Using: Arg List
execle() Execute Program Using: Arg List, Environment
execlp() Execute Program Using: Arg List, PATH
execlpe() Execute Program Using: Arg
execv() Execute Program Using: Arg Array
execve() Execute Program Using: Arg Array, Environment
execvp() Execute Program Using: Arg Array, PATH
execvpe() Execute Program Using: Arg
exit() Terminate Process after Cleanup
_exit() Terminate Process without Cleanup
exp() Calculate Exponential
expl() Calculate Long Double Exponential
fabs() Calculate Absolute Value of Floating Point
fabsl() Calculate Long Double Absolute Value of Floating Point
fclose() Close a Stream
fcloseall() Close All Open Streams
fcvt() Convert Double to String
fdopen() Open a Stream Using a Handle
feof() Detect Stream EndofFile (Macro)
ferror() Test for Error on a Stream (Macro)
fflush() Flush a Stream
fgetc() Read a Character from a Stream
fgetchar() Read a Character from Stdin
fgetpos() Get stream position indicator
fgets() Read a String from Stream
fieeetomsbin() Convert IEEE SinglePrecision to MS Binary
filelength() Return File Length
fileno() Get File Handle Associated with Stream (Macro)
floor() Calculate Floor of Value
floorl() Calculate Floor of Long Double Value
flushall() Flush All Streams and Clear All Buffers
fmod() Calculate FloatingPoint Remainder
fmodl() Calculate Long Double Floating Point Remainder
fmsbintoieee() Convert MS Binary SinglePrecision to IEEE
fopen() Open a File
FP_OFF() Get or Set Offset Portion of Far Pointer (Macro)
FP_SEG() Get or Set Segment Portion of Far Pointer (Macro)
_fpreset() Reinitialize FloatingPoint Math Package
fprintf() Write Formatted Data to Stream
fputc() Write a Character to a Stream
fputchar() Write a Character to Stdout
fputs() Write a String to Stream
fread() Read Unformatted Data from Stream
freopen() Reassign a File Pointer
frexp() Get Mantissa and Exponent of FloatingPoint Value
frexpl() Long Double Precision frep()
fscanf() Read Formatted Data from Screen
fseek() Reposition File Pointer to Given Location
fsetpos() Set Stream Position Indicator
_fsopen() Open File as a Stream
fstat() Get Information about Open File
_fstrcat() Append a String (Model Independent)
_fstrchr() Find a Character in a String (Model Independent)
_fstrcmp() Compare Two Strings (Model Independent)
_fstrcpy() Copy One String to Another (Model Independent)
_fstrcspn() Scan One String for Another (Model Independent)
_fstrdup() Duplicate String (Model Independent)
_fstricmp() Compare Two Strings (Model, Case Independent)
_fstrlen() Get String Length (Model Independent)
_fstrlwr() Convert String to Lower Case (Model Independent)
_fstrncat() Append n Characters (Model Independent)
_fstrncmp() Compare n Characters (Model Independent)
_fstrncpy() Copy n Characters (Model Independent)
_fstrnicmp() Compare n Characters (Model, Case Independent)
_fstrnset() Initialize n Characters (Model Independent)
_fstrpbrk() Scan for Char From Set (Model Independent)
_fstrrchr() Find Last Occurance of Char (Model Independent)
_fstrrev() Reverse a String (Model Independent)
_fstrset() Set Characters in String (Model Independent)
_fstrspn() Find First Substring (Model Independent)
_fstrstr() Find Substring (Model Independent)
_fstrtok() Finds Next Token in String (Model Independent)
_fstrupr() Convert to Upper Case (Model Independent)
ftell() Get Current File Pointer Position
ftime() Get Current System Time as Structure
_fullpath() Get Full Pathname
fwrite() Write Unformatted Data to Stream
gcvt() Convert Double to String
getc() Read a Character from a Stream (Macro)
getchar() Read a Character from 'Stdin'
getch() Get a Character from the Console without Echo
getche() Get a Character from Console with Echo
getcwd() Get Path Name of Current Working Directory
_getdcwd() Get Pathname of Current Directory Including Drive
getenv() Get a Value from the Environment Table
_getdrive() Get Current Working Drive
getpid() Get Process ID
gets() Read a Line from 'Stdin'
getw() Read an Integer from a Stream
gmtime() Convert Time from Long Integer to Structure
_harderr() Install new hardware error handler
_hardresume() Return to DOS after a hardware error
_hardretn() Return to Application After Hardware Error
hypot() Calculate the Hypotenuse of a Right Triangle
hypotl() Calclulate Long Double Hypotenuse
inp() Read a Byte from the Specified Port
inpw() Read word from I/O port
isalnum() Test for Alphanumeric Character (Macro)
isalpha() Test for Alphabetic Character (Macro)
isascii() Test for ASCII Character (Macro)
isatty() Check for Character Device
iscntrl() Test for Control Character (Macro)
isdigit() Test for Digit (Macro)
isgraph() Test for Printable Character Except Space (Macro)
islower() Test for Lowercase (Macro)
isprint() Test for Printable Character (Macro)
ispunct() Test for Punctuation Character (Macro)
isspace() Test for WhiteSpace Character (Macro)
isupper() Test for Uppercase (Macro)
isxdigit() Test for Hexadecimal Digit (Macro)
itoa() Convert Integer to String
kbhit() Check Keyboard Input Buffer for Character Waiting
labs() Calculate Absolute Value of Long Integer
ldexp() Convert Mantissa and Exponent to Floating Point
ldexpl() Convert Mantissa and Exponent into Long Double
ldiv() Divides long integers
lfind() Linear Search for Key
localeconv() Get Locale Setting Information
localtime() Convert Time from Long to StructureLocal Correc.
locking() Lock Areas of File
log() Calculate Natural Logarithm
logl() Calculate Long Double Natural Logarithm
log10() Calculate Base 10 Logarithm
log10l() Calculate Long Double Base 10 Logarithm
longjmp() Restore Program State
_lrotl() Shift a Long Int to the Left
_lrotr() Shift a Long Int to the Right
lsearch() Perform Linear Search
lseek() Reposition File Pointer to Specified Location
ltoa() Convert Long to String
_makepath() Make Path Name from Components
matherr() Handle Math Error
_matherrl() Handle Long Double Math Error
max() Return the Larger of Two Arguments (Macro)
min() Return the Smaller of Two Arguments (Macro)
mkdir() Create a New Directory
mktemp() Create a Unique File Name
mktime() Convert Time to Calendar Value
modf() Split Floating Point into Mantissa and Exponent
_modfl() Split Long Double in Mantissa and Exponent
movedata() Copy Characters to a Different Segment
_nstrdup() Duplicate String (Model Independent)
onexit() Register Terminating Function
open() Open a File
outp() Write a Byte to the Specified Port
outpw() Write Word to I/O Port
_pclose() Close a Stream (OS/2)
perror() Print Error Message
_pipe() Create a Pipe (OS/2)
_popen() Open a Stream (OS/2)
pow() Calculate X Raised to the Yth Power
powl() Calculate Long Double X Raised to the Yth Power
printf() Write Formatted String to Stdout
putc() Write a Character to Stream (Macro)
putchar() Write a Character to Stdout (Macro)
putch() Write a Character to the Console
putenv() Create New Environment Variables
puts() Write String to Stdout
putw() Write an Integer to Stream
qsort() Perform Quick Sort
raise() Send a Signal to Executing Program
rand() Get Pseudorandom Integer
read() Read Data from File
remove() Delete A File
rename() Rename a File or Directory
rewind() Reposition File Pointer to Beginning of Stream
rmdir() Remove a Directory
rmtmp() Remove Temporary File Created by tempfile()
_rotl() Shift an Int to the Left
_rotr() Shift an Int to the Right
sbrk() Reset Break Value for Calling Process
scanf() Read Formatted Data from Stdin
_searchenv() Searches for a file using a path
segread() Return Current Values of Segment Registers
setbuf() Control Stream Buffering
setjmp() Save Program State
setlocale() Set the Locale
setmode() Set FileTranslation Mode
setvbuf() Control Stream Buffering and Buffer Size
signal() Set Interrupt Signal Handling
sin() Calculate Sine
sinh() Calculate Hyperbolic Sine
sinhl() Calculate Long Double Hyperbolic Sine
sinl() Calculate Long Double Sine
sopen() Open A File for File Sharing
spawn...() An Overview of the Eight Spawn Functions
spawnl() Execute Program Using: Arg List
spawnle() Execute Program Using: Arg List, Environment
spawnlp() Execute Program Using Arg List, PATH
spawnlpe() Execute Program Using Arg List, PATH, Environment
spawnv() Execute Program Using Arg Array
spawnve() Execute Program Using Arg Array, Environment
spawnvp() Execute Program Using Arg Array, PATH
spawnvpe() Execute Program Using Arg Array,PATH,Environment
_splitpath() Split Path Name into Components
sprintf() Write Formatted Data to String
sqrt() Calculate Square Root
sqrtl() Calculate Long Double Square Root
srand() Set Random Starting Point
sscanf() Read Formatted Data from String
stat() Get FileStatus Information on Named File
_status87() Get 8087/80287 FloatingPoint Status Word
strcat() Append a String
strchr() Find a Character in a String
strcmp() Compare Two Strings, Case Sensitive
strcmpi() Compare Two Strings, Case Insensitive
strcoll() Compare Strings in LocaleSpecific Way
strcpy() Copy One String to Another
strcspn() Scan One String for Another
_strdate() Copy System Date to String
strdup() Duplicate String
strerror() Save System Error Message
_strerror() Save System Error Message
strftime() Format Time Value into a String
stricmp() Compare Two Strings, Case Insensitive
strlen() Get String Length
strlwr() Convert String to Lower Case
strncat() Append Specified Number of Characters to a String
strncmp() Compare n Characters of 2 Strings, Case Sensitive
strnicmp() Compare n Characters of Strings, Case Insensitive
strncpy() Copy a Specified Number of Characters
strnset() Initialize n Characters of String
strpbrk() Scan String for Character from Character Set
strrchr() Scan String for Last Occurrence of Character
strrev() Reverse Characters in String
strset() Set All Characters in String
strspn() Find First Substring
strstr() Find Substring
_strtime() Copy System Time to String
strtod() Convert String to Double
strtok() Finds Next Token in String
strtol() Convert String to Long Decimal Integer
_strtold() Convert String to Long Double
strtoul() Convert String to Unsigned Long
strupr() Convert String to Uppercase
strxfrm() Translate String According to Locale
swab() Swap Bytes
system() Execute DOS Command
tan() Calculate Tangent
tanh() Calculate Hyperbolic Tangent
tanhl() Calculate Long Double Hyperbolic Tangent
tanl() Calculate Long Double Tangent
tell() Get Current File Pointer Position
tempnam() Generate a Temporary File Name in Given Directory
time() Get Current System Time as Long Integer
tmpfile() Create a Temporary File
tmpnam() Generate a Temporary File Name
toascii() Convert 'c' to ASCII Character (Macro)
tolower() Convert 'c' to lowercase, if Appropriate (Macro)
_tolower() Convert 'c' to Lowercase (Macro)
toupper() Convert 'c' to Uppercase, if Appropriate (Macro)
_toupper() Convert 'c' to Uppercase (Macro)
tzset() Set External Time and Environment Variables
ultoa() Convert Unsigned Long to String
umask() Set Default Permission Mask
ungetc() Push Character Back onto the Stream
ungetch() Push Back Last Character Read from the Console
unlink() Delete a File
utime() Set FileModification Time
va_arg() Access Variable Number of Arguments, UNIX V Style
va_arg() Access Variable Number of Arguments, ANSI C Style
va_end() Resets arg_ptr to NULL
va_start() Sets arg_ptr to First Optional Argument
vfprintf() Write Formatted Data to Stream
vprintf() Write Formatted Data to Stdout
vsprintf() Write Formatted Data to String
wait() Suspend Calling Process Until Child Terminates
write() Write Data to a File
_arc() Draw an arc
_arc_w() Draw an arc (window coords)
_arc_wxy() Draw an arc (window pair coords)
_clearscreen() Clear screen to background color
_displaycursor() Cursor on/off on graphics exit
_ellipse() Draw an ellipse
_ellipse_w() Draw an ellipse (window coords)
_ellipse_wxy() Draw an ellipse (window pair coords)
_floodfill() Fill area with current color
_floodfill_w() Fill area with color (window coords)
_getactivepage() Get currently active screen page
_getarcinfo() Get last arc's parameters
_getbkcolor() Get current background color
_getcolor() Get current color
_getcurrentposition() Get current graphic output position
_getcurrentposition_w() Get output position (window coords)
_getfillmask() Get current fill mask
_getfontinfo() Get font characteristics
_getgtextextent() Get graphics text length in pixels
_getimage() Store a screen image in memory
_getimage_w() Store a screen image (window coords)
_getimage_wxy() Store a screen image (window pair coords)
_getlinestyle() Get line style
_getlogcoord() Translate Physical to Logical Coordinates
_getphyscoord() Convert logical to physical coordinates
_getpixel() Get a pixel value
_getpixel_w() Get a pixel value (window coords)
_gettextcolor() Get current text color
_gettextcursor() Get current cursor shape
_gettextposition() Get current text output position
_gettextwindow() Get boundaries of current text window
_getvideoconfig() Get current graphics environment
_getviewcoord() Translate physical to view coordinates
_getviewcoord_w() Translate window to view coordinates
_getviewcoord_wxy() Translate window pair to view coordinates
_getvisualpage() Get visual page number
_getwindowcoord() Translate view to window coordinates
_getwritemode() Get current logical write mode
_grstatus() Get most recent graphics errors
_imagesize() Return an image size (in bytes)
_imagesize_w() Return an image size (window coords)
_imagesize_wxy() Return an image size (window pair coords)
_lineto() Draw a line
_lineto_w() Draw a line (window coords)
_moveto() Move graphic output position
_moveto_w() Move output position (window coords)
_outgtext() Output graphic text
_outmem() Output characters from a buffer
_outtext() Display text at current position
_pg_analyzechart() Fill chart environment with data
_pg_analyzechartms() Fill chart environment with series of data
_pg_analyzepie() Fill chart environment for a pie chart
_pg_analyzescatter() Fill chart environment for a scatter chart
_pg_analyzescatterms() Fill multiple scatter chart environment
_pg_chart() Display a bar, column, or line chart
_pg_chartms() Display multiple bar, column, or line chart
_pg_chartpie() Display a pie chart
_pg_chartscatter() Display a scatter chart
_pg_chartscatterms() Display multiple series scatter chart
_pg_defaultchart() Initialize chart environment variable
_pg_getchardef() Get character definition
_pg_getpalette() Get palette colors and characteristics
_pg_getstyleset() Get current style
_pg_hlabelchart() Write horizontal chart label
_pg_initchart() Initialize presentation graphics
_pg_resetpalette() Reset palette characteristics to default
_pg_resetstyleset() Reset the styleset to default
_pg_setchardef() Set character definition
_pg_setpalette() Set palette characteristics
_pg_setstyleset() Set the styleset
_pg_vlabelchart() Write vertical chart label
_pie() Draw a pieslice shape
_pie_w() Draw a pie slice shape (window coords)
_pie_wxy() Draw a pie slice (window pair coords)
_polygon() Draw a polygon
_polygon_w() Draw a polygon (window coords)
_polygon_wxy() Draw a polygon (window pair coords)
_putimage() Retrieve and display a screen image
_putimage_w() Retrieve and display image (window coords)
_rectangle() Draw a rectangle
_rectangle_w() Draw a rectangle (window coords)
_rectangle_wxy() Draw a rectangle (window pair coords)
_registerfonts() Initialize the font graphics system
_remapallpalette() Assign colors to all pixel values
_remappalette() Assign colors to selected pixel values
_scrolltextwindow() Scroll current text window
_selectpalette() Select predefined palette
_setactivepage() Set memory area for writing images
_setbkcolor() Set background color
_setcliprgn() Set clipping region
_setcolor() Set color
_setfillmask() Set fill mask
_setfont() Set current font
_setgtextvector() Set font orientation
_setlinestyle() Set line style
_setlogorg() Set the Logical Position Origin
_setpixel() Set a pixel value
_setpixel_w() Set a pixel value (window coords)
_settextcolor() Set the text color
_settextcursor() Set the text cursor shape
_settextposition() Set new text output position
_settextrows() Set number of text rows
_settextwindow() Set up text window
_setvideomode() Set screen display mode
_setvideomoderows() Find appropriate screen mode
_setvieworg() Set the viewpoint origin
_setviewport() Set clipping region, reset origin
_setvisualpage() Set memory area for displaying pages
_setwindow() Define a window
_setwritemode() Set logical graphics write mode
_unregisterfonts() Remove font registration
_wrapon() Enable or disable text line wrap