1 epsii 59:006 spring 2004 2 final exam breakdown (approximate) pointers: 2 functions and parameter...

73
1 EPSII 59:006 Spring 2004

Upload: homer-simpson

Post on 18-Jan-2016

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

1

EPSII

59:006

Spring 2004

Page 2: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

2

Final Exam Breakdown (Approximate)

Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments: 1 input/output: 3 Structures: 2 Enumerations: 1 File I/O: 5 Arrays: 2 storage classes: 2 Number base conversions: 3 Arithmetic expression evaluation: 3 MATLAB: 12 Other: 4

Page 3: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

3

Final

59:006 Final Exam--Exam Period 30 (7:00 -9:00 p.m., Friday, May 14): Section AAA (Braun) will meet in Room 100 PH,

Section BBB (Kuhl) will meet in Shaumbaugh Auditorium Section CCC (Rodgers) will meet in Room 1505 SC.

Bring a #2 pencil Multiple choice Approximately 50 questions Comprehensive

Page 4: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

4

Note

This review contains more than 100 slides. It is possible that any material from these slides

may appear on the exam. However, these slides are not comprehensive (if

it was in a previous lecture, or in the text, or in an assignment – it is fair game).

Finally, since we cannot possibly cover 100++ slides in 50 minutes, we attempted to focus on important topics.

Page 5: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

5

Anatomy of a C Program

Since last exam, two key categories were covered:

Data Structures

Input Output

Page 6: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

6

Key Areas Addressed in Recent Lectures

Data Structures/Storage Input Output

Page 7: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

7

Data Structures

Data Types Arrays Structures

Page 8: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

8

Data Types

Variables are names for places in memory

There are different types of variables

Different variables require different amounts of information to store them

In C the main types are:

char, int, float, double

Page 9: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

9

Standard Variable Type Storage

Type Used For Storage (bytes)

int Integers 4 (usually, but is really

implementation-dependent)

char Characters 1

float Real numbers 4

double Real numbers 8

Page 10: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

10

Arrays Array

Group of consecutive memory locations Same name and type

To refer to an element, specify Array name Position number

Format:

arrayname[ position number ] First element at position 0 n element array named c:

c[0], c[1]...c[n – 1]

Name of array (Note that all elements of this array have the same name, c)

Position number of the element within array c

c[6]

-45

6

0

72

1543

-89

0

62

-3

1

6453

78

c[0]

c[1]

c[2]

c[3]

c[11]

c[10]

c[9]

c[8]

c[7]

c[5]

c[4]

Page 11: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

11

Passing Arrays to Functions Passing arrays

To pass an array argument to a function, specify the name of the array without any brackets

int myArray[24];

myFunction( myArray, 24 ); Array size usually passed to function

Arrays are passed as call-by-reference Name of array (unsubscripted) is address of first element Function knows where the array is stored

Modifies original memory locations Passing array elements

Passed by call-by-value Pass subscripted name (i.e., myArray[3]) to function

Page 12: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

12

Static Storage Class Static storage

Variables exist for entire program executionDefault initial value of zeroCan specify an alternative initial value:

static int x = 1; Static variables are initialized once, at beginning of

program execution.Static local variables defined in functions:

Keep value after function ends Only known in their own function

Page 13: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

13

Declaring & Initializing Arrays Initializers

int n[5] = { 1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements become 0

int n[5] = { 0 } All elements 0

If there are too many initializers, a syntax error occurs C arrays have no bounds checking

This means that using an invalid subscript will kill your program with the dreaded ‘Segmentation Fault’ runtime error.

If the array size is omitted in a definition, initializers determine itint n[] = { 1, 2, 3, 4, 5 }; // bad style

5 initializers, therefore 5 element array Don’t do this!!!!

The following is an illegal declaration, since the size isn’t specified

int n[]; /* error – no size given */

Page 14: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

14

Passing Arrays to Functions

Function prototype

void myFunction( int b[], int arraySize ); Parameter names optional in prototype

int b[] could be written int [] int arraySize could be simply int

Don’t specify array bounds inthe prototype or function header

Page 15: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

15

Multi-subscripted Arrays as function parameters

int twoDexample(int array2[ ] [10], int rows) {

Second subscriptmust be specifiedAs a constant

First subscriptmust be blank

For array parameters with more than two subscripts all but the first must be specified as constants in the function prototype and header

Int fourDexample(int [ ] [10] [5] [8], int);

Page 16: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

16

Multiple-Subscripted Arrays

Multiple subscripted arrays Tables with rows and columns (m by n array) Like matrices: specify row, then column

Row 0Row 1Row 2

Column 0 Column 1 Column 2 Column 3

a[ 0 ][ 0 ]

a[ 1 ][ 0 ]

a[ 2 ][ 0 ]

a[ 0 ][ 1 ]

a[ 1 ][ 1 ]

a[ 2 ][ 1 ]

a[ 0 ][ 2 ]

a[ 1 ][ 2 ]

a[ 2 ][ 2 ]

a[ 0 ][ 3 ]

a[ 1 ][ 3 ]

a[ 2 ][ 3 ]

Row subscriptArray name

Column subscript

Page 17: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

17

Multiple-Subscripted Arrays

Initialization int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Initializers grouped by row in braces If not enough, unspecified elements set to zero

int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements

Specify row, then column

printf( "%d", b[ 0 ][ 1 ] );

 

1 2

3 4

1 0

3 4

Page 18: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

18

Setup: A 2-D array

int a[3][5] =

{{1324, 140, 82, 201, 72},

{3124, 156, 70, 177, 74},

{5495, 128, 68, 222, 60}};

Page 19: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

19

C Storage Classes

auto (automatic) register static extern (external)

Page 20: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

20

Automatic Storage Class Automatic storage

Variable created and destroyed within its block If an initializer is used, the variable is reinitialized each time its

block is entered.

Default for local variables of functions

auto double x, y; register: tries to put variable into high-speed registers

(not of much significance for modern compilers and computers)

Can only be used for automatic variables

register int counter = 1;

Page 21: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

21

The #define directive

Note the use of #define preprocessor directive in preceding example: #define SIZE 10

Enhances readability and facilitates easy changes to program

Equates the symbolic name TEN with the constant 10Everyplace you use the string ‘TEN” I you program, the preprocessor will replace it with 10

Page 22: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

22

Pointer Operators & (address operator)

References the address of a variable

int y = 5;

int *yPtr;

yPtr = &y; // yPtr gets address of y

yPtr “points to” y

yPtr

y

5

yptr

500000 600000

y

600000 5

Address of y is value of yptr

Page 23: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

23

Calling Functions by Reference Call by reference with pointer arguments

Pass address of argument using & operator Allows you to change actual location in memory Arrays are not passed with & because the array name is already a

pointer * operator

Used as alias/nickname for variable inside of function

void double( int *number )

{

*number = 2 * ( *number );

} *number used as nickname for the variable passed

Page 24: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

24

Pointer Expressions and Pointer Arithmetic

5 element int array on machine with 4 byte ints vPtr points to first element v[ 0 ]

at location 3000 (vPtr = 3000) vPtr += 2; sets vPtr to 3008

vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte ints, so it points to address 3008

pointer variable vPtr

v[0] v[1] v[2] v[4]v[3]

3000 3004 3008 3012 3016location

 

Page 25: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

25

Arrays of Pointers Arrays can contain pointers ("an array of pointers") For example: an array of strings

char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };

Strings are pointers to the first character char * – each element of suit is a pointer to a char The strings are not actually stored in the array suit, only

pointers to the strings are stored

suit array has a fixed size, but strings can be of any size

suit[3]

suit[2]

suit[1]

suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

 

Page 26: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

26

Call by Value/Call by Reference

Generally, you don’t want to change the value of the parameter(s) you pass to a function

Y = sqrt(x) + x;

You don’t want the value of x to change when this function is called.

However, sometimes you want to—e.g.:

swapValues(&x, &y);

Page 27: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

27

Call-by-Value This is the most common way to pass

parameters

y = cos(x) ; The value of x is passed to the function but the

function cannot modify the value of x. Pass-by-value parameters insure that the

function will not have unintended “side effects”. Call-by-value should be used whenever possible

Page 28: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

28

Call-by-reference When a function needs to assign new value to a parameter,

call-by-reference parameter passage is used;

changeValue (&x) ; // The ‘&’ designates call-by-ref. By passing the address of x, the function can change its

value – we’ll see how later. Call-by-reference should be used with care since it can

result in subtle logic bugs that are difficult to diagnose. Note that we have already seen an example of call-by

reference: scanf(“%d”, &x); // Aha!! So, that’s’ why the ‘&’ is needed.

Page 29: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

29

Call-by Reference– A simple exampleA function that swaps the value of two variablesFirst, a version that DOESN’T work:

void swap( int , int);

int main(void) {

int x = 3; int y = 5; printf(“x=%d y=%d\n”, x,y); swap(x, y); printf(“x=%d y=%d\n”, x,y); }

void swap(int a, int b) { int temp; temp = a; a = b; b = temp; }

x=3 y=5x=3 y=5

swap has no effect on thevalues of x and y due topass-by-value parameterpassage

Page 30: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

30

Call-by-reference– a simple example

void swap( int *, int *);

int main(void) {

int x = 3; int y = 5; printf(“x=%d y=%d\n”, x,y); swap(&x, &y); printf(“x=%d y=%d\n”, x,y); }

void swap(int *a, int *b) {

}

x=3 y=5x=5 y=3

Now, a version of swap that works:

Page 31: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

31

Call-by-reference– a simple example

void swap( int *, int *);

int main(void) {

int x = 3; int y = 5; printf(“x=%d y=%d\n”, x,y); swap(&x, &y); printf(“x=%d y=%d\n”, x,y); }

void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; }

x=3 y=5x=5 y=3

Now, a version of swap that works:

Page 32: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

32

Structures

Structures Collections of related variables (aggregates) under one name

Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and

trees

Page 33: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

33

Structure Definitions Example

struct car { char make[10]; char model[10];

int year; };

struct introduces the definition for structure car car is the structure name and is used to declare variables of the

structure type car contains two members of type char *, and int

These members are make and model year

Page 34: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

34

Clarification: “char* face” VS “char face[10]” for hw10struct card1 {

char *face; char *suit; };

struct card2 { char face[10]; char suit[10]; };

main() { char *c4 = "Four"; char *hearts = "Hearts";

struct card1 threeHearts; threeHearts.face = "Three"; threeHearts.suit = hearts; printf("face = %s\n",threeHearts.face);

struct card2 fourDiamonds; strcpy(fourDiamonds.face , c4); // THIS commented line will NOT work // fourDiamonds.face = c4; // because space has been allocated in structure strcpy(fourDiamonds.suit , "diamonds"); printf("face = %s\n",fourDiamonds.face);}

Note the need to usestrcpy () to assign valuesto face and suit since theyhave been declared as arrays

Page 35: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

35

Accessing Members of Structures Accessing structure members

Dot operator (.) used with structure variables

struct card myCard = { "Three", "Hearts" };

printf( "%s", myCard.suit ); Arrow operator (->) used with pointers to structure variables

struct card *myCardPtr = &myCard;

printf( "%s", myCardPtr->suit ); myCardPtr->suit is equivalent to

( *myCardPtr ).suit

Page 36: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

36

Enumerations

User-defined data type Provide symbolic names for a range of

integer values Primary function is to improve program

readability

Page 37: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

37

Enumerations

enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

Example:

// sets JAN to 0, FEB to 1, … , DEC to 11)enum months month...

for (month = JAN; month < =DEC; month ++) { …}

Page 38: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

38

Strings and Characters String declarations

Declare as a character array or a variable of type char *char color[] = "blue";char *colorPtr = "blue";

Remember that strings represented as character arrays end with '\0'

color has 5 elements Inputting strings

Use scanfchar word[10];scanf("%s", word);

Copies input into word[] Do not need & (because word is a pointer)

Remember to leave room in the array for '\0'

Page 39: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

39

Chars as Ints Since characters are stored in one-byte ASCII

representation, they can be considered as one-byte integers.

C allows chars to be treated as ints and vice versa—e.g.:int main() { int ivar; char cvar; ivar = ‘b’; cvar = 97; printf (“ivar=%d cvar=‘%c’\n”, ivar, cvar);

}

ivar=98 cvar=‘a’

Page 40: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

40

Streams

Streams Sequences of characters organized into lines

Each line consists of zero or more characters and ends with newline character

ANSI C must support lines of at least 254 characters Performs all input and output Can often be redirected

Standard input – keyboard Standard output – screen Standard error – screen

Page 41: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

41

Scope Rules Block scope

Identifier declared inside a block {…} Block scope begins at declaration, ends at right

brace Used for:

local variables function parameters

Can actually define local variables in any C block (not recommended)

Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block

Function prototype scope Used for identifiers in parameter list

Page 42: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

42

Input-Output Options

Command Line Arguments scanf fgets pipe command Input/Output Redirection Shell Command Sequential files Random access files

Page 43: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

43

Important Use of Array of Strings—Command Line Arguments

We’ve used ‘int main(void)’ all semester as the main function header, but there is another form that can be used.

int main(int argc, char *argv[ ]){ argc counts how many words are on the command line

when the program was invoked. argv is an array of character strings, one word per element. When program is run, operating system places the name of

the program in argv[0] and any additional “command line arguments” in successive elements of argv[]

Page 44: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

44

#include <stdio.h>

int main(int argc, char *argv[ ]) { int i; printf(“The # of command line args is: %d\n”, argc); for (i = 0; i < argc; i++) printf("Argument %d is '%s'\n", i, argv[i]); return(0);

}

Example of Command Line Arguments

mainArgs.c

Page 45: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

45

Compile & Run:%gcc mainArgs.c –o mainArgs %mainArgsThe # of command line args is: 1argument 0 is ‘mainArgs’%mainArgs with argumentsThe # of command line args is: 3argument 0 is ‘mainArgs’argument 1 is ‘with’argument 2 is ‘arguments’%mainArgs 1234The # of command line arguments is: 2argument 0 is ‘mainArgs’argument 1 is ‘1234’

Page 46: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

46

Formatting Input with scanf scanf

Input formatting Capabilities

Input all types of data Input specific characters Skip specific characters

Format scanf(format-control-string, other-arguments);

Format-control-string Describes formats of inputs

Other-arguments Pointers to variables where input will be stored

Can include field widths to read a specific number of characters from the stream

Page 47: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

47

Formatting Input with scanfConversion specifier Description

Integers

d Read an optionally signed decimal integer. The corresponding argument is a pointer to integer.

i Read an optionally signed decimal, octal, or hexadecimal integer. The corresponding argument is a pointer to integer.

o Read an octal integer. The corresponding argument is a pointer to unsigned integer.

u Read an unsigned decimal integer. The corresponding argument is a pointer to unsigned integer.

x or X Read a hexadecimal integer. The corresponding argument is a pointer to unsigned integer.

h or l Place before any of the integer conversion specifiers to indicate that a short or long integer is to be input.

Floating-point numbers

e, E, f, g or G Read a floating-point value. The corresponding argument is a pointer to a floating-point variable.

l or L Place before any of the floating-point conversion specifiers to indicate that a double or long double value is to be input.

Page 48: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

48

Inputting Strings using scanf

char word[10];char *wptr;…// This is OK as long as input string is less // than 10 characters in lengthscanf(“%s”, word);

// But this is not, since wptr does not have associated // storage locations to hold the stringscanf(“%s”, wptr);

//This would be OK:wptr = word;scanf(“%s”, wptr);

Page 49: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

49

Files and Streams Read/Write functions in standard library

fgetc Reads one character from a file Takes a FILE pointer as an argument fgetc( stdin ) equivalent to getchar()

fputc Writes one character to a file Takes a FILE pointer and a character to write as an

argument fputc( 'a', stdout ) equivalent to putchar( 'a' )

fgets Reads a line from a file (terminated by newline character)

fputs Writes a line to a file

fscanf / fprintf File processing equivalents of scanf and printf

Page 50: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

50

UNIX input/output cat is most useful when directly taking the output from

one program and sending it as the input to another cat file | ./a.out

If file already exists,use the Input Redirection Shell Command, < % a.out argvstuff < dictionary.file

Can do the same for output (Output Redirection Shell Command %a.out argvstuff <dictionary.file >inclass

Page 51: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

51

Creating a Sequential Access File C imposes no file structure

No notion of records in a file Programmer must provide file structure

Creating a File FILE *myPtr;

Creates a FILE pointer called myPtr myPtr = fopen("myFile.dat", openmode);

Function fopen returns a FILE pointer to file specified Takes two arguments – file to open and file open mode If open fails, NULL returned

fprintf Used to print to a file Like printf, except first argument is a FILE pointer (pointer to the file

you want to print in)

Page 52: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

52

Creating a Sequential Access File feof( FILE pointer )

Returns true if end-of-file indicator (no more data to process) is set for the specified file

fclose( FILE pointer ) Closes specified file Performed automatically when program ends Good practice to close files explicitly

Details Programs may process no files, one file, or many files Each file must have a unique name and should have its own pointer

Page 53: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

53

Reading Data from a Sequential Access File

Reading a sequential access file Create a FILE pointer, link it to the file to read

myPtr = fopen( "myFile.dat", "r" ); Use fscanf to read from the file

Like scanf, except first argument is a FILE pointerfscanf( myPtr, "%d%s%f", &myInt, &myString,

&myFloat ); Data read from beginning to end File position pointer

Indicates number of next byte to be read / written Not really a pointer, but an integer value (specifies byte

location) Also called byte offset

rewind( myPtr ) Repositions file position pointer to beginning of file (byte 0)

Page 54: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

54

Random Access Files Random access files

Access individual records without searching through other records Instant access to records in a file Data can be inserted without destroying other data Data previously stored can be updated or deleted without overwriting

Implemented using fixed length records Sequential files do not have fixed length records

0 200 300 400 500

byte offsets}

} } } } } }

100

100bytes

100bytes

100bytes

100bytes

100bytes

100bytes

Page 55: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

55

Creating a Random Access File

Data in random access files Unformatted (stored as "raw bytes")

All data of the same type (ints, for example) uses the same amount of memory

All records of the same type have a fixed length Data not human readable

Page 56: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

56

Creating a Random Access File Unformatted I/O functions

fwrite Transfer bytes from a location in memory to a file

fread Transfer bytes from a file to a location in memory

Example:

fwrite( &number, sizeof( int ), 1, myPtr ); &number – Location to transfer bytes from sizeof( int ) – Number of bytes to transfer 1 – For arrays, number of elements to transfer

In this case, "one element" of an array is being transferred myPtr – File to transfer to or from

Page 57: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

57

Creating a Random Access File Writing structs

fwrite( &myObject, sizeof (struct myStruct), 1, myPtr );

sizeof – returns size in bytes of object in parentheses To write several array elements

Pointer to array as first argument Number of elements to write as third argument

Page 58: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

58

Define struct

Initialize variable

Initialize struct

Open file

Write to file using unformatted output

Close file

1 /* Fig. 11.11: fig11_11.c

2 Creating a randomly accessed file sequentially */

3 #include <stdio.h>

4

5 struct clientData {

6 int acctNum;

7 char lastName[ 15 ];

8 char firstName[ 10 ];

9 double balance;

10 };

11

12 int main()

13 {

14 int i;

15 struct clientData blankClient = { 0, "", "", 0.0 };

16 FILE *cfPtr;

17

18 if ( ( cfPtr = fopen( "credit.dat", "w" ) ) == NULL )

19 printf( "File could not be opened.\n" );

20 else {

21

22 for ( i = 1; i <= 100; i++ )

23 fwrite( &blankClient,

24 sizeof( struct clientData ), 1, cfPtr );

25

26 fclose( cfPtr );

27 }

28

29 return 0;

30 }

Page 59: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

59

Writing Data Randomly to a Random Access File

fseek Sets file position pointer to a specific position fseek( pointer, offset, symbolic_constant );

pointer – pointer to file offset – file position pointer (0 is first location) symbolic_constant – specifies where in file we are reading

from SEEK_SET – seek starts at beginning of file SEEK_CUR – seek starts at current location in file SEEK_END – seek starts at end of file

Page 60: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

60

Define struct

Initialize variables

Open file

Input data

Write to file

1 /* Fig. 11.12: fig11_12.c2 Writing to a random access file */3 #include <stdio.h>45 struct clientData { 6 int acctNum;7 char lastName[ 15 ];8 char firstName[ 10 ];9 double balance;10 };11 12 int main() 13 { 14 FILE *cfPtr;15 struct clientData client = { 0, "", "", 0.0 };1617 if ( ( cfPtr = fopen( "credit.dat", "r+" ) ) == NULL )18 printf( "File could not be opened.\n" );19 else { 20 printf( "Enter account number"21 " ( 1 to 100, 0 to end input )\n? " );22 scanf( "%d", &client.acctNum );2324 while ( client.acctNum != 0 ) { 25 printf( "Enter lastname, firstname, balance\n? " );26 fscanf( stdin, "%s%s%lf", client.lastName, 27 client.firstName, &client.balance );28 fseek( cfPtr, ( client.acctNum - 1 ) * 29 sizeof( struct clientData ), SEEK_SET );30 fwrite( &client, sizeof( struct clientData ), 1, 31 cfPtr );32 printf( "Enter account number\n? " );

Page 61: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

61

Close file

Program Output

33 scanf( "%d", &client.acctNum );

34 }

35

36 fclose( cfPtr );

37 }

38

39 return 0;

40 }

Enter account number (1 to 100, 0 to end input)? 37Enter lastname, firstname, balance? Barker Doug 0.00Enter account number? 29Enter lastname, firstname, balance? Brown Nancy -24.54Enter account number? 96Enter lastname, firstname, balance? Stone Sam 34.98

Page 62: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

62

Program Output

Enter account number? 88Enter lastname, firstname, balance? Smith Dave 258.34Enter account number? 33Enter lastname, firstname, balance? Dunn Stacey 314.33Enter account number? 0

Page 63: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

63

Reading Data Sequentially from a Random Access File

fread Reads a specified number of bytes from a file into memory

fread( &client, sizeof (struct clientData), 1, myPtr );

Can read several fixed-size array elements Provide pointer to array Indicate number of elements to read

To read multiple elements, specify in third argument

Page 64: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

64

Define struct

Initialize variables

Read (fread)

Print

1 /* Fig. 11.15: fig11_15.c2 Reading a random access file sequentially */3 #include <stdio.h>45 struct clientData { 6 int acctNum;7 char lastName[ 15 ];8 char firstName[ 10 ];9 double balance;10 };1112 int main()13 { 14 FILE *cfPtr;15 struct clientData client = { 0, "", "", 0.0 };1617 if ( ( cfPtr = fopen( "credit.dat", "r" ) ) == NULL )18 printf( "File could not be opened.\n" );19 else { 20 printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name",21 "First Name", "Balance" );2223 while ( !feof( cfPtr ) ) { 24 fread( &client, sizeof( struct clientData ), 1, 25 cfPtr );2627 if ( client.acctNum != 0 )28 printf( "%-6d%-16s%-11s%10.2f\n", 29 client.acctNum, client.lastName, 30 client.firstName, client.balance );31 }32

Page 65: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

65

Close file

Program Output

33 fclose( cfPtr );34 }3536 return 0;37 }

Acct Last Name First Name Balance29 Brown Nancy -24.5433 Dunn Stacey 314.3337 Barker Doug 0.0088 Smith Dave 258.3496 Stone Sam 34.98

Page 66: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

66

Program Output

Enter account to update (1 - 100): 3737 Barker Doug 0.00 Enter charge (+) or payment (-): +87.9937 Barker Doug 87.99

Enter new account number (1 - 100): 22Enter lastname, firstname, balance? Johnston Sarah 247.45

After choosing option 1 accounts.txt contains:

Acct Last Name First Name Balance29 Brown Nancy -24.5433 Dunn Stacey 314.3337 Barker Doug 0.0088 Smith Dave 258.3496 Stone Sam 34.98

Page 67: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

67

Printing Integers Integer

Whole number (no decimal point): 25, 0, -9 Positive, negative, or zero Only minus sign prints by default (later we shall change this)

Conversion Specifier Description

d Display a signed decimal integer.

i Display a signed decimal integer. (Note: The i and d specifiers are different when used with scanf.)

o Display an unsigned octal integer.

u Display an unsigned decimal integer.

x or X Display an unsigned hexadecimal integer. X causes the digits 0-9 and the letters A-F to be displayed and x causes the digits 0-9 and a-f to be displayed.

h or l (letter l) Place before any integer conversion specifier to indicate that a short or long integer is displayed respectively. Letters h and l are more precisely called length modifiers.

Page 68: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

68

Printing with Field Widthsand Precisions

Field width Size of field in which data is printed If width larger than data, default right justified

If field width too small, increases to fit data Minus sign uses one character position in field

Integer width inserted between % and conversion specifier %4d – field width of 4

Page 69: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

69

Printing with Field Widthsand Precisions

Field width and precision Can both be specified

%width.precision

%5.3f Negative field width – left justified Positive field width – right justified Precision must be positive Can use integer expressions to determine field width and precision

values Place an asterisk (*) in place of the field width or precision

Matched to an int argument in argument list Example:

printf( "%*.*f", 7, 2, 98.736 );

Page 70: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

70

Using Flags in the printfFormat-Control String

Flags Supplement formatting capabilities Place flag immediately to the right of percent sign Several flags may be combined

Flag Description

- (minus sign) Left-justify the output within the specified field.

+ (plus sign) Display a plus sign preceding positive values and a minus sign preceding negative values.

space Print a space before a positive value not printed with the + flag.

# Prefix 0 to the output value when used with the octal conversion specifier o.

Prefix 0x or 0X to the output value when used with the hexadecimal conversion specifiers x or X.

Force a decimal point for a floating-point number printed with e, E, f, g or G that does not contain a fractional part. (Normally the decimal point is only printed if a digit follows it.) For g and G specifiers, trailing zeros are not eliminated.

0 (zero) Pad a field with leading zeros.

Page 71: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

71

Printing String Literalsand Escape Sequences

Table of all escape sequences

Escape sequence Description

\' Output the single quote (') character.

\" Output the double quote (") character.

\? Output the question mark (?) character.

\\ Output the backslash (\) character.

\a Cause an audible (bell) or visual alert. \b Move the cursor back one position on the current line. \f Move the cursor to the start of the next logical page. \n Move the cursor to the beginning of the next line. \r Move the cursor to the beginning of the current line. \t Move the cursor to the next horizontal tab position. \v Move the cursor to the next vertical tab position.

Page 72: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

72

Relevant Textbook Readings for Final—Deitel & Deitel Chapters 1-6 Chapter 7 -- except Section 7.12 (pointers to functions) Chapter 8 – except Section 8.9 (memory functions of the

string handling library) Chapter 9 Chapter 10, sections 10.1 thru 10.7, and 10.11 only Chapter 11 Chapter 14, sections 14.2, 14.4 only

Page 73: 1 EPSII 59:006 Spring 2004 2 Final Exam Breakdown (Approximate) Pointers: 2 functions and parameter passage: 4 String processing: 5 Command line arguments:

73

Relevant MATLAB Readings for Final Exam (Etter’s text) Chapters 1-4 Chapter 6, sections 6.3-6.5 only