1 / 60

Advanced UNIX

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

strom
Download Presentation

Advanced UNIX

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Overview 1. Standard Library Header Files 2. Examining Characters (ctype.h) 3. Strings (string.h) 4. Maths (math.h) 5. Utilities (stdlib.h) 6. Timing (time.h)

  3. 1. Standard Library Header Files File Contentsstdio.h I/O and file operationsmath.h Mathematical functionsstring.h String functionsctype.h Character class testsstdlib.h Utility functions continued

  4. assert.h Assertions (debugging)setjmp.h Non-local jumps e.g. gotos out of functions signal.hSignal handlingerrno.h Error handlingtime.h Time and date functionsstdarg.h Variable-length argument lists e.g. as used by scanf(), printf() continued

  5. stddef.h Standard definitions e.g. size_t, NULL limits.h Implementation limits e.g. max / min values for different types float.h Floating point constants e.g. precision information locale.h Locality issues (language, etc.) e.g. non-english symbols, money symbol

  6. 2. Examining Characters (ctype.h) Function Character Classisalpha(c) Letterisdigit(c) Digitisalnum(c) Letter or digitislower(c) Lower case letterisupper(c) Upper case letterisspace(c) Space, ‘\f’, ‘\n’, ‘\r’, ‘\t’. ‘\v’tolower(c) Output lower case versiontoupper(c) Output upper case version : :

  7. Example int c;c = getchar();if (isalpha(c)) c = tolower(c);

  8. 3. Strings (string.h) 3.1. Common Functions 3.2. Limited Length Functions 3.3. Rarely Used (but Useful) 3.4. String Functions in stdio.h 3.5. Memory Functions

  9. 3.1. Common Functions Function Meaningchar *strcpy(d, s) Copy s to dchar *strcat(d, s) Append s onto end of dint strlen(s) Length of sint strcmp(s1, s2) Compare s1 and s2: 0 if s1 same as s2 < 0 if s1 < s2 > 0 if s1 > s2

  10. Example char s1[20];char s2[13] = “ Andrew”;strcpy(s1, “Hello”); /* s1 = “Hello”; is wrong */strcat(s1, s2);if (strcmp(s1, s2) == 0) printf(“the same\n”);

  11. 3.2. Limited Length Functions Function Meaningint strncmp(s1, s2, n)Compare at most n charschar *strncpy(d, s, n)Copy at most n chars of s to dchar *strncat(d, s, n)Append at most n chars of s to end of d

  12. Example char *s1 = “hello;char *s2 = “help”;if (strncmp(s1, s2, 3) == 0) printf(“First 3 chars the same\n”);

  13. 3.3. Rarely Used (but Useful) Function Meaningchar *strchr(s1,c) Find first c in s1char *strrchr(s1, c) Find last c in s1char *strstr(s1, s2) Find s2 in s1 (string search)char *strtok(s1, s2)Tokenise s1 using s2 as delimitor :

  14. s Examples http://foo.com/~ad nm char *s = “http://foo.com/~ad”;char *nm;if ((nm = strrchr(s, ‘/’)) != NULL) printf(“Name: %s\n”, nm+1); /* prints "~ad" */ if (strstr(s, “foo.com”) == NULL) printf(“Not a foo.com address\n”); continued

  15. #define SEP “ “ /* space is separator */char *s=“hello world, jim”;char *token;token = strtok(s, SEP); /* get 1st token */while (token != NULL) { printf(“token: %s\n”, token); token = strtok(NULL, SEP); /* get next token */} s is modified

  16. 3.4. String Functions in stdio.h • int sprintf(char *str, char *format, ...);int sscanf(char *str, char *format, ...); • Like printf() and scanf() but they use str not stdout / stdin • char s[100]; char *nm = “Andrew”;int age= 38;sprintf(s, “Hello %s, age: %d\n”, nm, age);

  17. 3.5. Memory Functions Function Meaningint memcmp(s1, s2, n) Compare first n chars of s1 and s2int memcpy(s1, s2, n) Copy n bytes from s2 to s1int memmove(s1, s2, n) Like memcpy() but s1 and s2 can overlap

  18. Usage • s1 and s2 are of type void * • can be supplied with pointers to anything • Typical use is to manipulate complex data structures efficiently by referring to their location and byte size in memory. • For string manipulation use str***functions.

  19. Example • #define SIZE 100typedef struct { ...} Stude;Stude a[SIZE], b[SIZE];Stude s1, s2;memcpy(b, a, SIZE*sizeof(Stude)); /* copy a to b */memcpy(&s2, &s1, sizeof(Stude)); /* copy s1 to s2 */ args must be pointers

  20. 4. Maths (math.h) • These functions are fairly basic • no complex arithmetic, matrix manipulation • Almost all the functions manipulate doubles. • Your code should use doubles: • efficiency, accuracy, portability

  21. Compilation • Some compilers do not link in the maths library automatically. • If you get a load/link error, try: $ gcc -o examp examp.c -lm Refers to the library /usr/lib/libm.so

  22. Error Handling • Maths functions can generate two kinds of errors: • domain errors • range errors • Domain error: caused when a function is given an input argument outside of its range • e.g. sqrt(-1.0) • errno set to EDOM continued

  23. Range error: caused when a function underflows or overflows • e.g. pow(2,1234567) • errno set to ERANGE • functions that overflow return HUGE_VAL(with a + or -) • no portable way to detect underflow

  24. 4.1. Simple Maths Functions Function Meaningsqrt(x) square root of xfabs(x) absolute value of xfmod(x,y) float remainder of x/yceil(x) ceiling of x • ceil(1.4) == 2.0 ceil(-1.4) == -1.0 floor(x) floor of x • floor(1.4) == 1.0 floor(-1.4) == -2.0

  25. 4.2. Trigonometry Function Meaningsin(x) sine of xcos(x) cosine of xtan(x) tangent of xasin(x) sin-1 x in range [-p/2, p/2]acos(x) cos-1 x in range [0, p]atan(x) tan-1 x in range [- p/2, p/2]atan2(x,y) tan-1 (x/y) in range [- p, p] x must be inrange [-1,1]

  26. 4.3. Exponential Function Meaningexp(x) expow(x,y) xylog(x) logexlog10(x) log10x • pow() returns a domain error if x==0 and y<=0 or if x<0 and y is a non-integer • log functions return a domain error if x==0 and a range error if x<0

  27. 5. Utilities (stdlib.h) • Contains functions for a range of tasks: • simple maths operations on integers • base conversion • dynamic memory allocation • random numbers • sorting / searching arrays • hooks to the system

  28. 5.1. Simple Maths Functions Function Meaningint abs(int x) absolute value of int xlong labs(long n) absolute value of long ndiv_t div(int x, int y) quotient and remainder of x/yldiv_t ldiv(long x, long y) same for longs • div_t and ldiv_t are structs with two fields • see stdlib.h

  29. 5.2. Converting Strings to Numbers Function Meaningint atoi(char *s) Convert s to intlong atol(char *s) Convert s to longdouble atof(char *s) Convert s to double • The strings must only contain decimal digits (and a sign); atof() knows exponents, fractions • Initial white space is skipped. • The conversion stops when the first illegal character is found.

  30. Example char *s1 = “ 23/7/1976”;char *s2= “23.1e2 is large”;int i;float f;i = atoi(s1); /* i == 23 */f = atof(s2); /* f == 23.1e2 */

  31. 5.3. Dynamic Memory Allocation Function Meaningvoid *malloc(int size) Create size bytes of storage; return pointer to it.void *calloc(int n, int size) Create n*size bytes of storage; return pointer to it. continued

  32. void free(void *addr) Deallocate storage pointed to by addr.void *realloc(void *old-addr, int new-size) Allocate new-size bytes of new storage; move storage at old-addr to new area; return pointer to it.

  33. Example typedef struct { int sno; /* student num */ char name[100];} Stude;Stude *s;s = (Stude *) malloc(100*sizeof(Stude));/* s points to 100 element Stude 'array' */s[0].sno = 1; /* s->sno = 1; */s = realloc(s, 200*sizeof(Stude));/* now a 200 element 'array' */

  34. 5.4. Random Number Function Meaningvoid srand(unsigned int seed) Set up the random number generator.int rand(void) Return a random number in range 0 to RAND_MAX

  35. Example int n; /* to be assigned values between 1 and 100 */srand( time(NULL) );/* standard 'trick' for getting a seed */n = rand() % 100 + 1; :n = rand() % 100 + 1;

  36. 5.5. Sorting • void qsort(void *arr, int n, int size,ptr_to_fn compare) • qsort() uses quicksort to sort any type of array (arr) of length n. size is the size of an array element. • compare is a pointer to a comparison function; it is used to compare two array elements.

  37. Comparison Type • typedef int (*ptr_to_fn)(void *, void *); • The comparison function takes two pointers to the array elements, and returns an integer: < 0 when first element < second 0 when first == second > 0 when first > second

  38. 5.5.1. Sort an integer array #define SIZE 5int a[SIZE] = {1, 3, 2, 0, 4}, i;qsort(a, SIZE, sizeof(int), icompare);for (i=0; i < SIZE; i++) printf(“%d “, a[i]); continued

  39. int icompare(const void *first, const void *second)/* icompare() gets pointers to the array elements */{ int f, s; f = *(int *) first; s = *(int *) second; return f - s; /* to fit return type */}

  40. 5.5.2. Sort an array of students typedef struct { int sno; /* student num */ char name[100];} Stude;#define SIZE 50Stude s[SIZE];/* ... fill in s[] */qsort(s, SIZE, sizeof(Stude), scompare); continued

  41. int scompare(const void *first, const void *second)/* scompare() gets pointers to the array elements */{ Stude f, s; f = *(Stude *) first; s = *(Stude *) second; return f.sno - s.sno;}

  42. 5.6. Searching Arrays • void *bsearch(void *key, void *arr, int n, int size,ptr_to_fn compare) • bsearch() uses binary search to search any type of sorted array (arr) of length n. size is the size of an array element. Search for an element like the one pointed to by key. • Result is a pointer to the found element or NULL. continued

  43. compare is a pointer to a comparison function; • it is used to compare two array elements: the key element and each array element. • Can often use the same comparison function as for sorting.

  44. 5.6.1. Search an integer array #define SIZE 5int a[SIZE] = {0, 1, 2, 3, 4};int find = 2; /* search for 2 in a[] */int *res;res = (int *) bsearch(&find, a, SIZE, sizeof(int), icompare);if (res != NULL) printf(“Found element %d\n”, &res);

  45. 5.6.2. Search for a student • First, we must create a student key which contains a student number. But no name is needed. Why? • Answer: the scompare function only compares student numbers • res will point to the matching student element in s[] (with snoandname values).

  46. #define SIZE 50Stude s[SIZE], key, *res;/* .... fill in s[] */ /* initialise key */key.sno = 4710092;res = (Stude *) bsearch(&key, s, SIZE, sizeof(Stude), scompare);if (res != NULL) printf(“Student no, name: %d, %s\n”, res->sno, res->name);

  47. 5.7. System Functions Function Meaningvoid exit(int i) Exit program, with i result (use 0 for success, non-0 for failure)int system(char *cmd) Execute OS command string in cmd

  48. Examples char s[100], *fnm = “foo.txt”;sprintf(s, “ls -l %s”, fnm);system(s); /* do ls -l foo.txt */ • Problem: Shell variables are not changed: • system (“cd .. ; ls”); /* correct */ • system(“cd ..”);system(“ls”); /* incorrect since no change to cwd after cd */ continued

  49. The Bourne shell is used to execute the command. • system() returns the termination status of the command. • We can read results using temporary files: system(“ls -l > temp”);if ((fp = fopen(“temp”, “r”)) != NULL) ... • there is another way: see popen() later

  50. 5.7.1. Access the environment: getenv() • Environment variables are shell variables that have been exported (with export in Bourne, setenv in C-Shell) • char *getenv(char *env-var); • Usage:printf(“Home is %s\n”, getenv(“HOME”));

More Related