1 / 29

Lecture 3

Lecture 3. System Programming in C. Lecture Summary. Streams Error handling Library functions Control flow Constants and macros Preprocessor Header files. Streams. What is a stream? Standard streams: stdin, stdout and stderr Other streams may be defined: FILE * fp;

eshana
Download Presentation

Lecture 3

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. Lecture 3 System Programming in C

  2. Lecture Summary • Streams • Error handling • Library functions • Control flow • Constants and macros • Preprocessor • Header files

  3. Streams • What is a stream? • Standard streams: stdin, stdout and stderr • Other streams may be defined: FILE * fp; • FILE type is defined in standard library, thus need to include it in each program that uses streams: #include <stdio.h>

  4. Working with Stream • Open it • Use it • Close it

  5. Opening the stream • FILE *fopen(char *filename, char *mode); • Mode • "r" open text file for reading • "w" create text file for writing; discard previous contents if any • "a" append; open or create text file for writing at end of file • "r+" open text file for update (i.e., reading and writing) • "w+" create text file for update, discard previous contents if any • "a+" append; open or create text file for update, writing at end • NULL (0) is returned in case of failure. • Example: FILE *stream1 = fopen (“c:\\myfile.txt”, “r”);

  6. Stream I/O • Printf, scanf, getchar, putchar, gets, puts works with stdin and stdout • Corresponding functions capable of working with any stream are: fprintf, fscanf, getc, putc, fgets, fputs – consume stream as an argument, for instance: int printf(const char *format, ...) int fprintf(FILE *stream, const char *format, ...) • Thus, following expressions give us the same result: printf ("test\n"); fprintf (stdout, "test\n");

  7. Closing the stream • fclose (FILE *fp); • Example: fclose(fp); • IMPORTANT – stream should be closed after usage.

  8. Standard streams Pre-defined streams need not be opened/closed by programmer • stdin – scanf, getchar, gets work with it • Can be re-directed: TEST1.EXE < INFILE.TXT • stdout – printf, putchar, puts work with it • Can be re-directed: TEST1.EXE > OUTFILE.EXE If both stdin & stdout need to be redirected, use: TEST1.EXE < INFILE.TXT > OUTFILE.EXE

  9. stderr • Another pre-defined stream • Does not have to be explicitly opened by the programmer. • Stderr is used for error messages. These messages are displayed on the screen by default, even when we redirect the program’s output (e.g. TEST1.EXE > OUTFILE.TXT). • To re-direct stderr: TEST1.EXE 2> OUTFILE.TXT if ( (fp=fopen(“c:\\infile.txt”,”r”)) == NULL) { fprintf(stderr,”Cannot open file\n”); exit(-1); }

  10. Library Functions • Library functions are commonly needed functions that have been predefined. • C has several standard function libraries • To use a library function, include the appropriate header file and link in the library during compilation. Example: #include <math.h> in “main.c” • Not including these files can lead to potential problems: Unless we add #include <math.h> the output to this program: main() { printf(“2 cubed is %f\n”,pow(2,3)); } is 0.000

  11. Standard libraries • Standard Libraries Math #include <math.h> String #include <string.h> Input/Output #include <stdio.h> Dynamic Memory Allocation #include <stdlib.h>

  12. Conditional execution A way to include conditional statements in the expressions Syntax: condition ? true_expression : false_expression Example: int x = y > z ? y : z; An alternative to: if (y > z) x = y else x = z;

  13. Pre & Post forms of ++ & -- • ++i first increments i and then returns its (incremented) value • i++ first returns value and then increments i • Example: int i=0, j=0; if (i++) printf ("i=0\n"); if (++j) printf ("j=0\n"); • As a standalone expressions, i++ and ++i are equivalent.

  14. Constants and Macros #define <ident> <token-sequence> #define <ident>(<params>) < token-sequence> • Syntax: no “=“ before (<params>) • Macros are expanded by the C preprocessor (e.g. every appearance of <ident> is replaced by <token-sequence>before compilation starts • Use: #define MAX_STR_LEN 20 #define IS_LOWER(c) ((c)>=‘a’ && (c)<=‘z’) #define TO_LOWER(c) ((c) – ‘a’ + ‘A’); char arr[MAX_STR_LEN+1], *str; …. for (str=arr;*str != ‘\0’; str++) { *str = TO_LOWER(*str); }

  15. Macros From the previous example: char arr[MAX_STR_LEN+1], *str; Is converted to: char arr[20+1], *str; And *str = TO_LOWER(*str); First to: *str = (IS_LOWER(*str) ? ((*str) - 'a' + 'A') : (*str) ); Then to: *str = (((*str)>='a' && (*str)<='z') ? ((*str) - 'a' + 'A') : (*str) ); And then compilation starts.

  16. Problems with Macros • Source of problems is that macros in general have no relation to C – they are just commands to pre-processor (I.e. – similar to scripts to text editor). • For instance, definition #define SQR(X) X*X has following sorts of problems • Operator Precedence Errors: SQR(a + b); is expanded to: a + b*a + b and not: (a + b)*(a + b) • Solution : Put parentheses (or braces) around Macro #define SQR(x) ((x) * (x))

  17. More problems with macros • Side Effects Errors: SQR(i++); expanded to: i++ * i++, which increments i twice. • Unnecessary Function Calls: SQR(long_function(a,b,c)); will evaluate the function twice. • There are no general solutions for the last two errors - so be cautious and wise !

  18. Calling a function Argument may always be an expression Arguments will not be modified Has fixed type Saves executable code May be passed as an argument to other functions Function call overhead Calling a macro May be a statement (require automatic variables) May have side-effectson args Operates (usually) on arguments ofvarying types Code is duplicated Cannot be passed as an argument No calling overhead Macros vs. Functions

  19. When to use macros, not functions? • Rules of Thumb: • operation required is short, simple and (maybe) used in different locations (files). • operation required is short, simple and is used intensively. • operation required is performed on variety of different types. • Examples: #define MAX(a,b) (((a)>(b)) ? (a) : (b)) #define SWAP(type,a,b) {type t=a; (a)=(b); (b)=t;}

  20. Enumerable Types Types that consist of certain integral values and are carried by symbolic names • enum definitions: enum bool {FALSE,TRUE}; enum month {JAN=1,FEB=2,…,DEC=12}; enum colors {WHITE=1,BLACK,GREEN=8,RED}; • Using enum types enum bool b[10]; enum cond = FALSE; • enum vs. #define ( enum is superior) - The compiler may check for type mismatch. - the debugger may recognize the symbolic names.

  21. Switch Statement switch (month) { case JAN: /* stmt */ … case DEC: printf(“31 days\n”); break; case APR: … case NOV: printf(“30 days\n”); break; … … case FEB: if (leap_year) printf(“29 days\n”); else printf(“28 days\n”); break; default: printf(“month error\n”); break; }

  22. break • Can also be used in for, while, do-while loops • break terminates these loops early, control transfers to the first stmt after the loop • Example: /* this function returns 1 if “a” is in increasing order, 0 otherwise */ int monotonic(int a[], int N) { int i; for (i=0; i<=N-1;i++) { if (a[i+1] < a[i]) break; } if (i==N) return 1; else return 0; }

  23. Continue • The continue statement transfers control to the next iteration of the loop. • Example: char s1[12] = “string1”; char s2[12] = “string2”; char m[12]; int i,count = 0; for (i=0;i<=12;i++) { if (s1[i] != s2[i]) continue; m[count++] = s1[i]; } printf(“%s\n”,m); /* m = ? */

  24. C Preprocessor • Program goes through preprocessor before other compilation • Preprocessor directives: • #include - include header files • #define - define constants or macros • #ifndef, #endif - conditional inclusion

  25. Header files • What are header files for? • Simple interface to previously defined functions (contain only declaration) • Modularity: code up small components, each with different functionality, and then link them together • Each component has a .c file and a .h file • The .c file has the function definitions. • The .h file has the function prototypes, constants definitions, macro definitions. • Easier to debug and to reuse

  26. Program structure func1.c func1.h func3.c func3.h func1.obj func1.obj #include “func1.h” #include “func2.h” #include “func3.h” main ()… main.c func3.c func3.h func3.obj main.obj

  27. Program building main.h main.h main.c with macros expanded, comments removed, .h files added, etc. Preprocessing main.c Compiling main.obj Code generated, Contains references to other object files & libraries main.exe Executable program main.obj Code generated, Contains references to other object files & libraries Linking

  28. Conditional text inclusions • A common use of #ifndef is in header files • It is usually harmful to include a header filemore then once (p1.cincludes h1.h thatincludes h2.h) • The way to prevent this is inserting thismacro at the beginning of every header fileyou write: #ifndef _header_name #define _header_name /* prevents entering here in future inclusions*/ … and then insert this line at the end of file: #endif

  29. Sample of multi-file program func1.c #include "func1.h" int sqr(int x) { return x * x; } main.c #include "func1.h" #include <stdio.h> main() { printf ("square of %d is %d\n", 2, sqr(2)); } func1.h #ifndef _FUNC1_H_ #define _FUNC1_H_ int sqr(int x); #endif // _FUNC1_H_

More Related