Unformatted text preview:

1CMSC 212 – S07 (lect 5)Announcementsz Program #1– Due Tuesday (2/13/07)z Reading– Chapter 9,10 (Today)• skip 9.3– Chapter 5 (Tuesday)2CMSC 212 – S07 (lect 5)Character Functionsz Prototypes in ctype.hz Classifying characters – parameter is int, but it's a character– int isspace(int ch);• returns true if ch ' ', '\n', '\t', form feed, or carriage return– int isdigit(int ch);• returns true if its 0 through 9– int islower(int ch), isupper(int ch)• return true if it’s a-z, A-Z– int isalpha(int ch)• returns true if it's a-z or A-Zz Transformation– int toupper(int ch), int tolower(int ch)• converts to upper/lower case3CMSC 212 – S07 (lect 5)Combining struct and typedefz Often useful to use typedef and struct together:typedef struct {int a;char b;float c;} Simple;z Declarations then look like:Simple x;Simple y[20], z;z Header Files– If structure used by more than one file, put it in a header file.– Use #include to include definition in each file where used.4CMSC 212 – S07 (lect 5)Accessing Fields of Structuresz Consider this definition:struct {int a;char b;float c;} x, y[10];z Simple structure access:– x.a = 3;– printf("field b = %c\n", x.b);z Accessing arrays of structures:– y[7].c = 3.14;– y[i].b = 'a';5CMSC 212 – S07 (lect 5)Initializing Entire Structuresz Consider:struct {int a;char b;float c;} x, y[3];z Can use { } to define and entire structurex = { 2, 'z', 3.14 };y = { { 1, 'a', 1.0 },{ 2, 'b', 2.0 },{ 3, 'c', 3.0 } };6CMSC 212 – S07 (lect 5)Abstract Data Typesz Key Idea: Hide implementation from users– lets implementation evolve without changing use– makes it easier to understand code• simply know what a function should do not howz Static keyword helps with this– hides global variables from other modules– hides functions that should not be called from other modules7CMSC 212 – S07 (lect 5)Bit Fieldsz Part of the Power of C is control over data layout– If you need a field with exactly 13 bits, you can define it– Useful for:– defining fields that interact with hardware– managing pre-defined file formats– saving every last bit of space– Syntax: type variable:size;z Examples:int foo:13;unsigned int foo:4;typedef struct { /* from project #1 */unsigned int opCode:4;unsigned int r1:4;unsigned int r2:4;unsigned int r3:4;unsigned int address:16;} instruction;8CMSC 212 – S07 (lect 5)Passing Structures as Argumentstypedef struct {char productName[200];int quantity;float unitPrice;} Transaction;void printReceipt( Transaction trans){printf("product = %s\n", trans.productName);printf(" quanity = %d\n", trans.quanity);printf(" price = %f\n", trans.unitPrice);}z Uses call by value– Entire structure is copied to printReceipt9CMSC 212 – S07 (lect 5)typedef struct {char productName[200];int quantity;float unitPrice;} Transaction;Transaction foo;void printReceipt( Transaction *trans){printf("product = %s\n", trans->productName);printf(" quanity = %d\n", trans->quanity);printf(" price = %f\n", trans->unitPrice);}printReceipt(&foo);Passing a reference to a StructureIndicates referenceIndicates pass only the reference10CMSC 212 – S07 (lect 5)Unionsz Syntax is similar to structsz Rather than storing each field, only stores one of the fields– Handy when need to stores different things based on criteriaz Syntax:– union tag { member-list } variable-listz Examples:union {float f;int i;} fi;fi.f = 3.14159;11CMSC 212 – S07 (lect 5)Variant Record Exampletypedef struct {enum { INT, FLOAT, NAME } type;union {int i;float f;char n[100];} u;} VariableType;12CMSC 212 – S07 (lect 5)Memory Allocationz Structures are placed in consecutive memory locations– memory is rounded up to alignment• characters take 1 bytes• integers normally take 4 bytes and start at aligned addressesz Can query the size of a structure or variable– sizeof(structure name) or sizeof(variable name)0x000x040x080x0c0x100x14struct {int a;char b;int c;} x;x = { 3, 'a', 10 };30000x61000???0xA13CMSC 212 – S07 (lect 5)Standard I/O Libraryz #include <stdio.h>– includes prototypes for standard I/O routinesz Most I/O is stream based– buffered to allow efficient operations • mostly to disks or networks– interactive I/O is normally flushed at useful points• printf("foo\n"); /* \n causes a flush */z FILE type– used to describe an active I/O connection– three default ones supplied on entry to main:• stdin - an input stream for default input (often keybaord)• stdout - default output stream (often terminal window) • stderr - default output stream for errors14CMSC 212 – S07 (lect 5)Opening Filesz FILE *fopen(char *name, char *mode)• name specifies the name of the file to open• mode specifies the access mode:– "r" - read (file must exist)– "w" - write (write, existing file deleted)– "a" - append (write, existing file left alone)– Check return code:• A NULL return implies and error• use perror(…) to report the cause of the errorz Example:FILE *fp;fp = fopen("foo", "r");if (!fp) {perror("foo");exit(-1);}15CMSC 212 – S07 (lect 5)Operations on FILEz int fclose(FILE *fp);– close a file (flushing any output if needed)– on success, returns 0• CAN FAIL!: On AFS (e.g., WAM) files not written to server until close.z Character I/O– int fgetc(FILE *stream);• return the next character from input (as an int)• returns EOF on end of file– EOF doesn't fit into a char– check for EOF before assigning result to char – int getchar(void);• like fgetc but reads from stdin.16CMSC 212 – S07 (lect 5)Character I/O (cont.)z int fputc(int character, FILE *stream);– write character to the destination named in stream– return EOF on failure, 0 on successz int putchar(int character);– like fputc but always uses stdout.z int ungetc(int character, FILE *stream);– if you read something, and want to put it back– next read will get this character– all implementations will support at least one ungetc• may support more, but not guaranteed– moving the file pointer will discard these• see fseek, etc. later in this lecture17CMSC 212 – S07 (lect 5)Line I/Oz Often useful to read and process an entire linez char *fgets(char *buffer, int bufferSize, FILE *stream);– read a line into buffer (at most bufferSize-1 characters)• null byte added at end of buffer– reads from stream– returns NULL on error or end of file– on success returns bufferz gets: never use this function!– it leads to buffer


View Full Document

UMD CMSC 212 - Lecture 5

Download Lecture 5
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 5 and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 5 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?