240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less...

60
40-491 Adv. UNIX: lib/12 Advanced UNIX Advanced UNIX Objectives of these slides: Objectives of these slides: look at look at some some of the less familiar of the less familiar functions in the ANSI C Standard functions in the ANSI C Standard Library Library 240-491 Special Topics in Comp. Eng. 1 Semester 2, 2000-2001 12. The Standard Libraries

Transcript of 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less...

Page 1: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 1

Advanced UNIXAdvanced UNIX

Objectives of these slides:Objectives of these slides:– look at look at somesome of the less familiar functions in of the less familiar functions in

the ANSI C Standard Librarythe ANSI C Standard Library

240-491 Special Topics in Comp. Eng. 1Semester 2, 2000-2001

12. The Standard Libraries

Page 2: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 2

OverviewOverview

1.1. Standard Library Header Files Standard Library Header Files

2. Examining Characters (2. Examining Characters (ctype.hctype.h))

3.3. Strings ( Strings (string.hstring.h))

4.4. Maths ( Maths (math.hmath.h))

5.5. Utilities ( Utilities (stdlib.hstdlib.h))

6. Timing (6. Timing (time.htime.h))

Page 3: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 3

1. Standard Library Header Files1. Standard Library Header Files

FileFile ContentsContentsstdio.hstdio.h I/O and file operationsI/O and file operationsmath.hmath.h Mathematical Mathematical functionsfunctionsstring.hstring.h String functionsString functionsctype.hctype.h Character class testsCharacter class testsstdlib.hstdlib.h Utility functionsUtility functions

continued

Page 4: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 4

assert.hassert.h Assertions (debugging)Assertions (debugging)setjmp.hsetjmp.h Non-local jumpsNon-local jumps

e.g. gotos out of functionse.g. gotos out of functions

signal.hsignal.h Signal handlingSignal handlingerrno.herrno.h Error handlingError handlingtime.htime.h Time and date functionsTime and date functionsstdarg.hstdarg.h Variable-length argument listsVariable-length argument lists

e.g. as used by e.g. as used by scanf()scanf(), , printf()printf()

continued

Page 5: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 5

stddef.hstddef.h Standard definitionsStandard definitions

e.g. e.g. size_tsize_t, , NULLNULL

limits.hlimits.h Implementation limitsImplementation limits

e.g. max / min values for different typese.g. max / min values for different types

float.hfloat.h Floating point constantsFloating point constants

e.g. precision informatione.g. precision information

locale.hlocale.h Locality issues (language, etc.)Locality issues (language, etc.)

e.g. non-english symbols, money symbole.g. non-english symbols, money symbol

Page 6: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 6

2. Examining Characters 2. Examining Characters ((ctype.h))

FunctionFunction Character ClassCharacter Classisalpha(c)isalpha(c) LetterLetterisdigit(c)isdigit(c) DigitDigitisalnum(c)isalnum(c) Letter or digitLetter or digitislower(c)islower(c) Lower case letterLower case letterisupper(c)isupper(c) Upper case letterUpper case letterisspace(c)isspace(c) Space, ‘\f’, ‘\n’, ‘\r’, ‘\t’. ‘\v’Space, ‘\f’, ‘\n’, ‘\r’, ‘\t’. ‘\v’tolower(c)tolower(c) Output lower case versionOutput lower case versiontoupper(c)toupper(c) Output upper case versionOutput upper case version

:: ::

Page 7: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 7

ExampleExample

int c;int c;

c = getchar();c = getchar();if (isalpha(c))if (isalpha(c)) c = tolower(c); c = tolower(c);

Page 8: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 8

3. Strings (3. Strings (string.h))

3.1. Common Functions3.1. Common Functions

3.2. Limited Length Functions3.2. Limited Length Functions

3.3. Rarely Used (but Useful)3.3. Rarely Used (but Useful)

3.4. String Functions in 3.4. String Functions in stdio.hstdio.h

3.5. Memory Functions3.5. Memory Functions

Page 9: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 9

3.1. Common Functions3.1. Common Functions

FunctionFunction MeaningMeaningchar *strcpy(d, s)char *strcpy(d, s) Copy s to dCopy s to d

char *strcat(d, s)char *strcat(d, s) Append s onto end of dAppend s onto end of d

int strlen(s)int strlen(s) Length of sLength of s

int strcmp(s1, s2)int strcmp(s1, s2) Compare s1 and s2:Compare s1 and s2: 00 if s1 same as s2if s1 same as s2 < 0< 0 if s1 < s2if s1 < s2 > 0> 0 if s1 > s2if s1 > s2

Page 10: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 10

ExampleExample

char s1[20];char s1[20];char s2[13] = “ Andrew”;char s2[13] = “ Andrew”;

strcpy(s1, “Hello”);strcpy(s1, “Hello”);/* s1 = “Hello”; is wrong *//* s1 = “Hello”; is wrong */

strcat(s1, s2);strcat(s1, s2);

if (strcmp(s1, s2) == 0)if (strcmp(s1, s2) == 0)printf(“the same\n”);printf(“the same\n”);

Page 11: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 11

3.2. Limited Length Functions3.2. Limited Length Functions

FunctionFunction MeaningMeaningint strncmp(s1, s2, n)int strncmp(s1, s2, n) CompareCompare at most at most

n charsn chars

char *strncpy(d, s, n)char *strncpy(d, s, n) CopyCopy at most n chars at most n charsof s to dof s to d

char *strncat(d, s, n)char *strncat(d, s, n) AppendAppend at most n at most n chars of s to end of dchars of s to end of d

Page 12: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 12

ExampleExample

char *s1 = “hello;char *s1 = “hello;char *s2 = “help”;char *s2 = “help”;

if (strncmp(s1, s2, 3) == 0)if (strncmp(s1, s2, 3) == 0) printf(“First 3 chars the same\n”); printf(“First 3 chars the same\n”);

Page 13: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 13

3.3. Rarely Used (but Useful)3.3. Rarely Used (but Useful)

FunctionFunction MeaningMeaningchar *strchr(s1,c)char *strchr(s1,c) Find Find firstfirst c in s1 c in s1char *strrchr(s1, c)char *strrchr(s1, c) Find Find lastlast c in s1 c in s1

char *strstr(s1, s2)char *strstr(s1, s2) Find s2 in s1Find s2 in s1((string searchstring search))

char *strtok(s1, s2)char *strtok(s1, s2) TokeniseTokenise s1 using s2 s1 using s2as delimitoras delimitor

::

Page 14: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 14

ExamplesExamples

char *s = “http://foo.com/~ad”;char *s = “http://foo.com/~ad”;char *nm;char *nm;

if ((nm = strrchr(s, ‘/’)) != NULL)if ((nm = strrchr(s, ‘/’)) != NULL) printf(“Name: %s\n”, nm+1); printf(“Name: %s\n”, nm+1); /* prints "~ad" */ /* prints "~ad" */

if (strstr(s, “foo.com”) == NULL)if (strstr(s, “foo.com”) == NULL) printf(“Not a foo.com address\n”); printf(“Not a foo.com address\n”);

http://foo.com/~ad

s

nm

continued

Page 15: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 15

#define SEP “ “#define SEP “ “ /* space is separator *//* space is separator */

char *s=“hello world, jim”;char *s=“hello world, jim”;char *token;char *token;

token = strtok(token = strtok(ss, SEP); /* get 1st token */, SEP); /* get 1st token */while (token != NULL) {while (token != NULL) { printf(“token: %s\n”, token); printf(“token: %s\n”, token); token = strtok( token = strtok(NULLNULL, SEP); /* get next token */, SEP); /* get next token */}}

s is modified

Page 16: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 16

3.4. String Functions in 3.4. String Functions in stdio.h

int sprintf(char *str, char *format, ...);int sprintf(char *str, char *format, ...);int sscanf(char *str, char *format, ...);int sscanf(char *str, char *format, ...);

Like Like printf()printf() and and scanf()scanf() but they but they use use strstr not not stdoutstdout / / stdinstdin

char s[100]; char s[100]; char *nm = “Andrew”;char *nm = “Andrew”;int age= 38;int age= 38;sprintf(s, “Hello %s, age: %d\n”, nm, sprintf(s, “Hello %s, age: %d\n”, nm, age);age);

Page 17: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 17

3.5. Memory Functions3.5. Memory Functions

FunctionFunction MeaningMeaningint memcmp(s1, s2, n)int memcmp(s1, s2, n) Compare first n charsCompare first n chars

of s1 and s2of s1 and s2

int memcpy(s1, s2, n)int memcpy(s1, s2, n) Copy n Copy n bytesbytes from froms2 to s1s2 to s1

int memmove(s1, s2, n)int memmove(s1, s2, n) Like Like memcpy()memcpy() but buts1 and s2 can overlaps1 and s2 can overlap

Page 18: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 18

UsageUsage s1s1 and and s2s2 are of type are of type void *void *

– can be supplied with pointers to anythingcan be supplied with pointers to anything

Typical use is to Typical use is to manipulate complex data manipulate complex data structures efficientlystructures efficiently by referring to their by referring to their location and byte size in memory.location and byte size in memory.

For string manipulation use For string manipulation use str***str***

functions.functions.

Page 19: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 19

ExampleExample #define SIZE 100#define SIZE 100typedef struct {typedef struct { ... ...} Stude;} Stude;

Stude a[SIZE], b[SIZE];Stude a[SIZE], b[SIZE];Stude s1, s2;Stude s1, s2;

memcpy(b, a, SIZE*sizeof(Stude)); memcpy(b, a, SIZE*sizeof(Stude)); /* copy a to b */ /* copy a to b */

memcpy(&s2, &s1, sizeof(Stude));memcpy(&s2, &s1, sizeof(Stude)); /* copy s1 to s2 */ /* copy s1 to s2 */

args must be pointers

Page 20: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 20

4. Maths (4. Maths (math.h))

These functions are fairly basicThese functions are fairly basic– no complex arithmetic, matrix manipulationno complex arithmetic, matrix manipulation

Almost all the functions manipulate Almost all the functions manipulate doubledoubles.s.

Your code should use Your code should use doubledoubles:s:– efficiency, accuracy, portabilityefficiency, accuracy, portability

Page 21: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 21

CompilationCompilation

Some compilers do not link in the maths Some compilers do not link in the maths library automatically. library automatically.

If you get a load/link error, try:If you get a load/link error, try:$ $ gcc -o examp examp.c gcc -o examp examp.c -lm-lm

Refers to the library/usr/lib/libm.so

Page 22: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 22

Error HandlingError Handling Maths functions can generate two kinds of Maths functions can generate two kinds of

errors:errors:– domain errorsdomain errors

– range errorsrange errors

Domain errorDomain error: caused when a function is given : caused when a function is given an input argument outside of its rangean input argument outside of its range– e.g. e.g. sqrt(-1.0)sqrt(-1.0)

– errnoerrno set to set to EDOMEDOM

continued

Page 23: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 23

Range errorRange error: caused when a function : caused when a function underflows or overflowsunderflows or overflows– e.g. e.g. pow(2,1234567)pow(2,1234567)

– errnoerrno set to set to ERANGEERANGE

– functions that overflow return functions that overflow return HUGE_VALHUGE_VAL (with a + or -)(with a + or -)

– no portable way to detect underflowno portable way to detect underflow

Page 24: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 24

4.1. Simple Maths Functions4.1. Simple Maths Functions

FunctionFunction MeaningMeaningsqrt(x)sqrt(x) square root of xsquare root of xfabs(x)fabs(x) absolute value of xabsolute value of xfmod(x,y)fmod(x,y) float remainder of x/yfloat remainder of x/y

ceil(x)ceil(x) ceiling of xceiling of x– ceil(1.4)ceil(1.4) == 2.0 ceil(-1.4) == -1.0== 2.0 ceil(-1.4) == -1.0

floor(x)floor(x) floor of xfloor of x– floor(1.4) == 1.0 floor(1.4) == 1.0 floor(-1.4) == -2.0floor(-1.4) == -2.0

Page 25: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 25

4.2. Trigonometry4.2. Trigonometry

FunctionFunction MeaningMeaningsin(x)sin(x) sine of xsine of xcos(x)cos(x) cosine of xcosine of xtan(x)tan(x) tangent of xtangent of x

asin(x)asin(x) sinsin-1-1 x in range [- x in range [-/2, /2, /2]/2]acos(x)acos(x) coscos-1-1 x in range [0, x in range [0, ]]atan(x)atan(x) tantan-1-1 x in range [- x in range [- /2, /2, /2]/2]atan2(x,y)atan2(x,y) tantan-1-1 (x/y) in range [- (x/y) in range [- , , ]]

x must be inrange [-1,1]

Page 26: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 26

4.3. Exponential4.3. ExponentialFunctionFunction MeaningMeaningexp(x)exp(x) eexx

pow(x,y)pow(x,y) xxyy

log(x)log(x) loglogeexx

log10(x)log10(x) loglog1010xx

pow()pow() returns a returns a domain errordomain error if if x==0x==0 and and y<=0y<=0 or if or if x<0x<0 and and yy is a non-integer is a non-integer

loglog functions return a functions return a domain errordomain error if if x==0x==0 and a and a range errorrange error if if x<0x<0

Page 27: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 27

5. Utilities (5. Utilities (stdlib.h))

Contains functions for a range of tasks:Contains functions for a range of tasks:– simple maths operations on integerssimple maths operations on integers– base conversionbase conversion– dynamic memory allocationdynamic memory allocation– random numbersrandom numbers– sorting / searching arrayssorting / searching arrays– hooks to the systemhooks to the system

Page 28: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 28

5.1. Simple Maths Functions5.1. Simple Maths Functions

FunctionFunction MeaningMeaningint abs(int x)int abs(int x) absolute value of int xabsolute value of int xlong labs(long n)long labs(long n) absolute value of long nabsolute value of long n

div_t div(int x, int y)div_t div(int x, int y)

quotient and remainder of x/yquotient and remainder of x/yldiv_t ldiv(long x, long y)ldiv_t ldiv(long x, long y)

same for longssame for longs

div_tdiv_t and and ldiv_tldiv_t are structs with two fields are structs with two fields– see see stdlib.hstdlib.h

Page 29: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 29

5.2. Converting Strings to Numbers5.2. Converting Strings to Numbers

FunctionFunction MeaningMeaningint atoi(char *s)int atoi(char *s) Convert s to intConvert s to intlong atol(char *s)long atol(char *s) Convert s to longConvert s to longdouble atof(char *s)double atof(char *s)Convert s to doubleConvert s to double

The strings must only contain decimal digits The strings must only contain decimal digits (and a sign); (and a sign); atof()atof() knows exponents, fractions knows exponents, fractions

Initial white space is skipped.Initial white space is skipped. The conversion stops when the first illegal character is The conversion stops when the first illegal character is

found.found.

Page 30: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 30

ExampleExample

char *s1 = “ 23/7/1976”;char *s1 = “ 23/7/1976”;char *s2= “23.1e2 is large”;char *s2= “23.1e2 is large”;int i;int i;float f;float f;

i = atoi(s1);i = atoi(s1); /* i == 23 *//* i == 23 */f = atof(s2);f = atof(s2); /* f == 23.1e2 *//* f == 23.1e2 */

Page 31: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 31

5.3. Dynamic Memory Allocation5.3. Dynamic Memory Allocation

FunctionFunction MeaningMeaningvoid *malloc(int size)void *malloc(int size) Create Create sizesize bytes bytes

of storage; returnof storage; returnpointer to it.pointer to it.

void *calloc(int n, int size)void *calloc(int n, int size)

Create Create n*sizen*size bytes bytes

of storage; returnof storage; returnpointer to it.pointer to it.

continued

Page 32: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 32

void free(void *addr)void free(void *addr) Deallocate storageDeallocate storagepointed to by pointed to by addraddr..

void *realloc(void *old-addr, void *realloc(void *old-addr, int new-size)int new-size)

Allocate Allocate new-sizenew-size bytes of new bytes of newstorage; move storage at storage; move storage at old-addrold-addr

to new area; return pointer to it.to new area; return pointer to it.

Page 33: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 33

ExampleExampletypedef struct {typedef struct { int sno; int sno; /* student num *//* student num */ char name[100]; char name[100];} Stude;} Stude;

Stude *s;Stude *s;

s = (Stude *) s = (Stude *) mallocmalloc(100*sizeof(Stude));(100*sizeof(Stude));/* s points to 100 element Stude 'array' *//* s points to 100 element Stude 'array' */s[0].sno = 1;s[0].sno = 1; /* s->sno = 1; *//* s->sno = 1; */

s = s = reallocrealloc(s, 200*sizeof(Stude));(s, 200*sizeof(Stude));/* now a 200 element 'array' *//* now a 200 element 'array' */

Page 34: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 34

5.4. Random Number5.4. Random Number

FunctionFunction MeaningMeaningvoid srand(unsigned int seed)void srand(unsigned int seed)

Set up the random Set up the random numbernumber

generator.generator.

int rand(void)int rand(void) Return a random numberReturn a random numberin range 0 to in range 0 to RAND_MAXRAND_MAX

Page 35: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 35

ExampleExample

int n;int n; /* to be assigned values /* to be assigned values between 1 and 100 */ between 1 and 100 */

srandsrand( time(NULL) );( time(NULL) );/* standard 'trick' for getting a seed *//* standard 'trick' for getting a seed */

n = n = randrand() % 100 + 1;() % 100 + 1;::

n = rand() % 100 + 1;n = rand() % 100 + 1;

Page 36: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 36

5.5. Sorting5.5. Sorting

void qsort(void *arr, int n, int size,void qsort(void *arr, int n, int size, ptr_to_fnptr_to_fn compare) compare)

qsort()qsort() uses uses quicksortquicksort to sort any type of array to sort any type of array ((arrarr) of length ) of length nn. . sizesize is the size of an array element. is the size of an array element.

comparecompare is a is a pointerpointer to a comparison function; to a comparison function; it is used to compare two array elements.it is used to compare two array elements.

Page 37: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 37

Comparison TypeComparison Type

typedef int (*typedef int (*ptr_to_fnptr_to_fn)(void *, void *);)(void *, void *);

The comparison function takes two pointers to The comparison function takes two pointers to the array elements, and returns an integer:the array elements, and returns an integer:

< 0< 0 when first element < secondwhen first element < second

00 when first == secondwhen first == second

> 0> 0 when first > secondwhen first > second

Page 38: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 38

5.5.1. Sort an integer array5.5.1. Sort an integer array

#define SIZE 5#define SIZE 5

int a[SIZE] = {1, 3, 2, 0, 4}, i;int a[SIZE] = {1, 3, 2, 0, 4}, i;

qsort(a, SIZE, sizeof(int), icompare);qsort(a, SIZE, sizeof(int), icompare);

for (i=0; i < SIZE; i++)for (i=0; i < SIZE; i++) printf(“%d “, a[i]); printf(“%d “, a[i]);

continued

Page 39: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 39

int icompare(const void *first, int icompare(const void *first, const void *second)const void *second)

/* icompare() gets pointers to the/* icompare() gets pointers to the array elements */ array elements */{{ int f, s; int f, s;

f = *(int *) first; f = *(int *) first; s = *(int *) second; s = *(int *) second;

return f - s; /* to fit return type */ return f - s; /* to fit return type */}}

Page 40: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 40

5.5.2. Sort an array of students5.5.2. Sort an array of students

typedef struct {typedef struct { int sno; int sno; /* student num *//* student num */ char name[100]; char name[100];} Stude;} Stude; #define SIZE 50#define SIZE 50

Stude s[SIZE];Stude s[SIZE];/* ... fill in s[] *//* ... fill in s[] */

qsort(s, SIZE, sizeof(Stude), scompare);qsort(s, SIZE, sizeof(Stude), scompare);

continued

Page 41: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 41

int scompare(const void *first, int scompare(const void *first, const void *second)const void *second)

/* scompare() gets pointers to the/* scompare() gets pointers to the array elements */ array elements */{{ Stude f, s; Stude f, s;

f = *(Stude *) first; f = *(Stude *) first; s = *(Stude *) second; s = *(Stude *) second;

return f.sno - s.sno; return f.sno - s.sno;}}

Page 42: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 42

5.6. Searching Arrays5.6. Searching Arrays void *bsearch(void *key, void *bsearch(void *key,

void *arr, int n, int size,void *arr, int n, int size,ptr_to_fnptr_to_fn compare) compare)

bsearch()bsearch() uses uses binary searchbinary search to search any type to search any type of of sortedsorted array ( array (arrarr) of length ) of length nn. . sizesize is the size is the size of an array element. Search for an element like of an array element. Search for an element like the one pointed to by the one pointed to by keykey..

Result is a Result is a pointerpointer to the found element or to the found element or NULL.NULL.

continued

Page 43: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 43

comparecompare is a pointer to a comparison function; is a pointer to a comparison function;– it is used to compare two array elements: the it is used to compare two array elements: the keykey

element and each array element.element and each array element.

Can often use the same comparison function Can often use the same comparison function as for sorting.as for sorting.

Page 44: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 44

5.6.1. Search an integer array5.6.1. Search an integer array

#define SIZE 5#define SIZE 5

int a[SIZE] = {0, 1, 2, 3, 4};int a[SIZE] = {0, 1, 2, 3, 4};int find = 2; /* search for 2 in a[] */int find = 2; /* search for 2 in a[] */int *res;int *res;

res = (int *) bsearch(&find, a, SIZE, res = (int *) bsearch(&find, a, SIZE, sizeof(int), sizeof(int), icompareicompare););

if (res != NULL)if (res != NULL) printf(“Found element %d\n”, &res); printf(“Found element %d\n”, &res);

Page 45: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 45

5.6.2. Search for a student5.6.2. Search for a student

First, we must create a student First, we must create a student keykey which which contains a student number. But no name is contains a student number. But no name is needed. needed. Why?Why?

AnswerAnswer: the : the scomparescompare function only compares function only compares student numbers student numbers

resres will point to the matching student element will point to the matching student element in in s[]s[] (with (with snosno andand namename values). values).

Page 46: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 46

#define SIZE 50#define SIZE 50Stude s[SIZE], key, *res;Stude s[SIZE], key, *res;/* .... fill in s[] *//* .... fill in s[] */

/* initialise key *//* initialise key */key.sno = 4710092;key.sno = 4710092;

res = (Stude *) bsearch(&key, s, SIZE, res = (Stude *) bsearch(&key, s, SIZE, sizeof(Stude), sizeof(Stude),

scomparescompare););

if (res != NULL)if (res != NULL) printf(“Student no, name: %d, %s\n”, printf(“Student no, name: %d, %s\n”,

res->sno, res->name);res->sno, res->name);

Page 47: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 47

5.7. System Functions5.7. System Functions

FunctionFunction MeaningMeaningvoid exit(int i)void exit(int i) Exit program, with Exit program, with ii result result

(use 0 for success, (use 0 for success, non-0 for failure)non-0 for failure)

int system(char *cmd)int system(char *cmd)

Execute OS commandExecute OS commandstring in string in cmdcmd

Page 48: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 48

ExamplesExamples

char s[100], *fnm = “foo.txt”;char s[100], *fnm = “foo.txt”;

sprintf(s, “ls -l %s”, fnm);sprintf(s, “ls -l %s”, fnm);system(s); /* do ls -l foo.txt */system(s); /* do ls -l foo.txt */

ProblemProblem: Shell variables are not changed:: Shell variables are not changed:– system (“cd .. ; ls”); /* correct */system (“cd .. ; ls”); /* correct */– system(“cd ..”);system(“cd ..”);system(“ls”);system(“ls”); /* incorrect since /* incorrect since

no change to cwd no change to cwd after cd */ after cd */

continued

Page 49: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 49

The Bourne shell is used to execute the The Bourne shell is used to execute the command.command.

system()system() returns the termination status of the returns the termination status of the command.command.

We can read results using temporary files:We can read results using temporary files:system(“ls -l > temp”);system(“ls -l > temp”);if ((fp = fopen(“temp”, “r”)) != NULL)if ((fp = fopen(“temp”, “r”)) != NULL) ... ...

– there is another way: see there is another way: see popen()popen() later later

Page 50: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 50

5.7.1. Access the environment: 5.7.1. Access the environment: getenv()

Environment variables are shell variables that Environment variables are shell variables that have been exported (with have been exported (with exportexport in Bourne, in Bourne, setenvsetenv in C-Shell) in C-Shell)

char *getenv(char *env-var);char *getenv(char *env-var);

Usage:Usage:printf(“Home is %s\n”, getenv(“HOME”));printf(“Home is %s\n”, getenv(“HOME”));

Page 51: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 51

From the From the envp main() argument argument

#include <stdio.h>#include <stdio.h>#include <stdlib.h>#include <stdlib.h>int main(int argc, char *argv[], int main(int argc, char *argv[],

char *envp[]char *envp[])){{ int i = 0; int i = 0; /* print out envp[] */ /* print out envp[] */ while (envp[i] != NULL) while (envp[i] != NULL) printf(“%s\n”, envp[i++]); printf(“%s\n”, envp[i++]); return 0; return 0;}}

continued

Page 52: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 52

Each Each envp[i]envp[i] contains a string of the form: contains a string of the form:name=valuename=value

Possible output:Possible output:HOME=/user/adHOME=/user/adSHELL=/bin/bashSHELL=/bin/bashTERM=vt100TERM=vt100USER=adUSER=ad : :

Page 53: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 53

5.7.2. popen() and and pclose() in in stdio.h

FILE *popen(char *cmd, char *mode);FILE *popen(char *cmd, char *mode);int pclose(FILE *fp);int pclose(FILE *fp);

Use Use popen()popen() to execute a command to execute a command andand open a open a pipepipe into it (or out of it). into it (or out of it).

The pipe can be manipulated using file The pipe can be manipulated using file I/O commands.I/O commands.

continued

Page 54: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 54

The pipe can be used to send input into The pipe can be used to send input into the command (or receive output from the the command (or receive output from the command).command).

pclose()pclose() closes the pipe and completes closes the pipe and completes the command.the command.

Page 55: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 55

Command input: Command input: wc

FILE *fp;FILE *fp;int numlines;int numlines;

if ((fp = popen(if ((fp = popen(“wc -l foo.c”“wc -l foo.c”, “, “rr”)) ”)) == NULL) {== NULL) {

perror(“popen() failure of wc”); perror(“popen() failure of wc”); exit(1); exit(1);}}fscanf(fp, “%d”, &numlines);fscanf(fp, “%d”, &numlines);pclose(fp);pclose(fp);

program

wc -l foo.cfp

Page 56: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 56

Command output: Command output: mail

FILE *fp;FILE *fp;char *mesg=“hello jim”;char *mesg=“hello jim”;

if ((fp = popen(“if ((fp = popen(“mail -s \”Hi\” mail -s \”Hi\” [email protected]@ratree.psu.ac.th”, ”,

““ww”)) == NULL) {”)) == NULL) { perror(“popen() failure of mail”); perror(“popen() failure of mail”); exit(1); exit(1);}}fprintf(fp, “%s\n”, mesg);fprintf(fp, “%s\n”, mesg);pclose(fp);pclose(fp);

program

mail -s "Hi"fp

Page 57: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 57

6. Timing (6. Timing (time.h))

time_t time(time_t *ptr)time_t time(time_t *ptr)

Common usage:Common usage:time_t t; /* usually same as int */time_t t; /* usually same as int */t = time(NULL);t = time(NULL);/* no. of secs since 1/1/1970 */ /* no. of secs since 1/1/1970 */

Most programs convert Most programs convert time_ttime_t values to values to struct tmstruct tm or or char *char * for better output. for better output.

Epoch time

Page 58: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 58

struct tm

Look in Look in time.htime.h::struct tm {struct tm { int tm_sec; int tm_sec; /* seconds *//* seconds */ int tm_min; int tm_min; /* minutes *//* minutes */ int tm_hour; int tm_hour; /* hours since midnight *//* hours since midnight */ int tm_mday; int tm_mday; /* day of month: 1..31 *//* day of month: 1..31 */ int tm_mon; int tm_mon; /* month since January: /* month since January:

0..11 */0..11 */ int tm_year; int tm_year; /* years since 1900 *//* years since 1900 */

::}}

Page 59: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 59

Conversion FunctionsConversion Functions struct_tm *localtime(time_t *tptr);struct_tm *localtime(time_t *tptr);char *ctime(time_t *tptr);char *ctime(time_t *tptr);

Usage:Usage:time_t t;time_t t;struct tm tv;struct tm tv;

t = t = timetime(NULL):(NULL):tv = tv = *localtime*localtime(&t);(&t);printf(“Day of month: %d\n”, tv.tm_mday);printf(“Day of month: %d\n”, tv.tm_mday);printf(“%s\n”, printf(“%s\n”, ctimectime(&t));(&t));

/* the ctime() output is like date *//* the ctime() output is like date */

Page 60: 240-491 Adv. UNIX: lib/121 Advanced UNIX v Objectives of these slides: –look at some of the less familiar functions in the ANSI C Standard Library 240-491.

240-491 Adv. UNIX: lib/12 60

Processor TimeProcessor Time clock_t clock(void)clock_t clock(void)

– returns the processor time (number of clock ticks) returns the processor time (number of clock ticks) used by the programused by the program since its execution began since its execution began

The number of clock ticks per second is defined in The number of clock ticks per second is defined in CLOCKS_PER_SECCLOCKS_PER_SEC..

Print execution time in seconds using:Print execution time in seconds using:– printf(“printf(“%f%f secs running\n”, secs running\n”,

(double) (clock()/CLOCKS_PER_SEC) ); (double) (clock()/CLOCKS_PER_SEC) );