高级 unix240491综合工程专题第一学期2000200_第1页
高级 unix240491综合工程专题第一学期2000200_第2页
高级 unix240491综合工程专题第一学期2000200_第3页
高级 unix240491综合工程专题第一学期2000200_第4页
高级 unix240491综合工程专题第一学期2000200_第5页
已阅读5页,还剩55页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Advanced UNIX,Objectives of these slides: look at some of the less familiar functions in the ANSI C Standard Library,240-491 Special Topics in Comp. Eng. 1Semester 2, 2000-2001,12. The Standard Libraries,Overview,1. Standard Library Header Files 2. Examining Characters (ctype.h) 3. Strings (string.h

2、) 4. Maths (math.h) 5. Utilities (stdlib.h) 6. Timing (time.h,1. Standard Library Header Files,FileContentsstdio.hI/O and file operationsmath.hMathematical functionsstring.hString functionsctype.hCharacter class testsstdlib.hUtility functions,continued,assert.hAssertions (debugging)setjmp.hNon-local

3、 jumps e.g. gotos out of functions signal.hSignal handlingerrno.hError handlingtime.hTime and date functionsstdarg.hVariable-length argument lists e.g. as used by scanf(), printf(,continued,stddef.hStandard definitions e.g. size_t, NULL limits.hImplementation limits e.g. max / min values for differe

4、nt types float.hFloating point constants e.g. precision information locale.hLocality issues (language, etc.) e.g. non-english symbols, money symbol,2. Examining Characters (ctype.h,FunctionCharacter Classisalpha(c)Letterisdigit(c)Digitisalnum(c)Letter or digitislower(c)Lower case letterisupper(c)Upp

5、er case letterisspace(c)Space, f, n, r, t. vtolower(c)Output lower case versiontoupper(c)Output upper case version,Example,int c;c = getchar();if (isalpha(c) c = tolower(c,3. Strings (string.h,3.1. Common Functions 3.2. Limited Length Functions 3.3. Rarely Used (but Useful) 3.4. String Functions in

6、stdio.h 3.5. Memory Functions,3.1. Common Functions,FunctionMeaningchar *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: 0if s1 same as s2 0if s1 s2,Example,char s120;char s213 = “ Andrew”;strcpy(s1, “Hello”);/* s1 = “Hello”

7、; is wrong */strcat(s1, s2);if (strcmp(s1, s2) = 0)printf(“the samen”,3.2. Limited Length Functions,FunctionMeaningint strncmp(s1, s2, n)Compare at mostn charschar *strncpy(d, s, n)Copy at most n charsof s to dchar *strncat(d, s, n)Append at most n chars of s to end of d,Example,char *s1 = “hello;ch

8、ar *s2 = “help”;if (strncmp(s1, s2, 3) = 0) printf(“First 3 chars the samen”,3.3. Rarely Used (but Useful,FunctionMeaningchar *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 s2as delimitor,Examp

9、les,char *s = “http:/ *nm;if (nm = strrchr(s, /) != NULL) printf(“Name: %sn”, nm+1); /* prints ad */ if (strstr(s, “”) = NULL) printf(“Not a addressn”,http:/,s,nm,continued,define SEP “ “/* space is separator */char *s=“hello world, jim”;char *token;token = strtok(s, SEP); /* get 1st token */while (

10、token != NULL) printf(“token: %sn”, token); token = strtok(NULL, SEP); /* get next token *,s is modified,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 s100; char *nm

11、= “Andrew”;int age= 38;sprintf(s, “Hello %s, age: %dn”, nm, age,3.5. Memory Functions,FunctionMeaningint memcmp(s1, s2, n)Compare first n charsof s1 and s2int memcpy(s1, s2, n)Copy n bytes froms2 to s1int memmove(s1, s2, n)Like memcpy() buts1 and s2 can overlap,Usage,s1 and s2 are of type void * can

12、 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,Example,define SIZE 100typedef struct . Stude;Stude aSIZE, bSIZE;Stude s1, s2;memcpy(b, a, SIZE*s

13、izeof(Stude); /* copy a to b */memcpy( /* copy s1 to s2 *,args must be pointers,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,Compilation,Some c

14、ompilers 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,Error Handling,Maths functions can generate two kinds of errors: domain errors range errors Domain error: caused when a function is given an i

15、nput argument outside of its range e.g. sqrt(-1.0) errno set to EDOM,continued,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,4.1. Simple Maths Functions,F

16、unctionMeaningsqrt(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,4.2. Trigonometry,FunctionMeaningsin(x)sine of xcos(x)cosine of xtan(x)tangent of xasin(x)sin-1 x

17、in range -p/2, p/2acos(x)cos-1 x in range 0, patan(x)tan-1 x in range - p/2, p/2atan2(x,y)tan-1 (x/y) in range - p, p,x must be inrange -1,1,4.3. Exponential,FunctionMeaningexp(x)expow(x,y)xylog(x)logexlog10(x)log10 x pow() returns a domain error if x=0 and y=0 or if x0 and y is a non-integer log fu

18、nctions return a domain error if x=0 and a range error if x0,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,5.1. Simple Maths Functions,Functio

19、nMeaningint 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,5.2. Converting Strings to Numbers,FunctionMeaningint atoi(cha

20、r *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,Example,char *s1

21、 = “ 23/7/1976”;char *s2= “23.1e2 is large”;int i;float f;i = atoi(s1);/* i = 23 */f = atof(s2);/* f = 23.1e2 *,5.3. Dynamic Memory Allocation,FunctionMeaningvoid *malloc(int size)Create size bytes of storage; returnpointer to it.void *calloc(int n, int size)Create n*size bytes of storage; returnpoi

22、nter to it,continued,void free(void *addr)Deallocate storagepointed to by addr.void *realloc(void *old-addr, int new-size)Allocate new-size bytes of newstorage; move storage at old-addrto new area; return pointer to it,Example,typedef struct int sno;/* student num */ char name100; Stude;Stude *s;s =

23、 (Stude *) malloc(100*sizeof(Stude);/* s points to 100 element Stude array */s0.sno = 1;/* s-sno = 1; */s = realloc(s, 200*sizeof(Stude);/* now a 200 element array *,5.4. Random Number,FunctionMeaningvoid srand(unsigned int seed)Set up the random rand(void)Return a random numberi

24、n range 0 to RAND_MAX,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,5.5. Sorting,void qsort(void *arr, int n, int size, ptr_to_fn compare) qsort() uses quicksort to sort any type of ar

25、ray (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,Comparison Type,typedef int (*ptr_to_fn)(void *, void *); The comparison function takes two pointers to the array elements, and returns an integer: 0wh

26、en first second,5.5.1. Sort an integer array,define SIZE 5int aSIZE = 1, 3, 2, 0, 4, i;qsort(a, SIZE, sizeof(int), icompare);for (i=0; i SIZE; i+) printf(“%d “, ai,continued,int icompare(const void *first, const void *second)/* icompare() gets pointers to the array elements */ int f, s; f = *(int *)

27、 first; s = *(int *) second; return f - s; /* to fit return type *,5.5.2. Sort an array of students,typedef struct int sno;/* student num */ char name100; Stude; #define SIZE 50Stude sSIZE;/* . fill in s */qsort(s, SIZE, sizeof(Stude), scompare,continued,int scompare(const void *first, const void *s

28、econd)/* scompare() gets pointers to the array elements */ Stude f, s; f = *(Stude *) first; s = *(Stude *) second; return f.sno - s.sno,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)

29、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,compare is a pointer to a comparison function; it is used to compare two array elements: the key element and each array element. Can oft

30、en use the same comparison function as for sorting,5.6.1. Search an integer array,define SIZE 5int aSIZE = 0, 1, 2, 3, 4;int find = 2; /* search for 2 in a */int *res;res = (int *) bsearch,5.6.2. Search for a student,First, we must create a student key which contains a student number. But no name is

31、 needed. Why? Answer: the scompare function only compares student numbers res will point to the matching student element in s (with sno and name values,define SIZE 50Stude sSIZE, key, *res;/* . fill in s */ /* initialise key */key.sno = 4710092;res = (Stude *) bsearch,5.7. System Functions,FunctionM

32、eaningvoid exit(int i)Exit program, with i result(use 0 for success, non-0 for failure)int system(char *cmd)Execute OS commandstring in cmd,Examples,char s100, *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”

33、); /* correct */ system(“cd .”);system(“ls”);/* incorrect since no change to cwd after cd *,continued,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”) !

34、= NULL) . there is another way: see popen() later,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 %sn”, getenv(“HOME”,From the envp main() argument,i

35、nclude #include int main(int argc, char *argv, char *envp) int i = 0; /* print out envp */ while (envpi != NULL) printf(“%sn”, envpi+); return 0,continued,Each envpi contains a string of the form: name=value Possible output: HOME=/user/adSHELL=/bin/bashTERM=vt100USER=ad,5.7.2. popen() and pclose() i

36、n stdio.h,FILE *popen(char *cmd, char *mode);int pclose(FILE *fp); Use popen() to execute a command and open a pipe into it (or out of it). The pipe can be manipulated using file I/O commands,continued,The pipe can be used to send input into the command (or receive output from the command). pclose() closes the pipe and completes the command,Command input: wc,FILE *fp;int numlines;if (fp = popen(“wc -l foo.c”, “r”) = NULL) perror(“popen() failure of

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论