c programming: advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfpointer...

73
Course Overview C Programming: Advanced C Programming: Advanced Instructor Jack Straub 425-888-9119 [email protected] http://faculty.washington.edu/jstraub Grading 80% Attendance 70% Successful completion of homework 70% Grade on final exam Recommended Textbook C: A Reference Manual, Fifth Edition, Samuel Harbison and Guy Steele. ISBN: 0-13-089592-X Schedule See web site Additional Recommended Readings See web site Course Overview file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...%20Work/AdvancedC/Binders/010Introduction/100Intro.html [3/29/2008 10:01:02 AM]

Upload: others

Post on 06-Oct-2020

32 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Course Overview

C Programming: Advanced

C Programming: Advanced ● Instructor

�❍ Jack Straub �❍ 425-888-9119 �❍ [email protected] �❍ http://faculty.washington.edu/jstraub

● Grading

�❍ 80% Attendance �❍ 70% Successful completion of homework �❍ 70% Grade on final exam

● Recommended Textbook

�❍ C: A Reference Manual, Fifth Edition, Samuel Harbison and Guy Steele. ISBN: 0-13-089592-X

● Schedule

�❍ See web site

● Additional Recommended Readings �❍ See web site

Course Overview

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...%20Work/AdvancedC/Binders/010Introduction/100Intro.html [3/29/2008 10:01:02 AM]

Page 2: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Homework Overview

Homework Overview

Homework Overview ● Schedule

�❍ 9 Assignments �❍ Due at the start of each class �❍ Late submissions are not accepted

● Grading

�❍ 0 to 20 points; 180 points total �❍ 70% of 180 = 126 points minimum passing grade

● Submission

�❍ All assignments submitted via the class drop box:

Homework Drop Box (home page)

● General

�❍ Two weeks for each assignment (except exercise 1) �❍ Sample solutions discussed/published at the start of each class

Homework Overview

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ork/AdvancedC/Binders/010Introduction/200Homework.html [3/29/2008 10:01:02 AM]

Page 3: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Structures

Structure Declaration

#define NAME_LEN (50)struct personnel_rect{ char last[NAME_LEN + 1]; char first[NAME_LEN + 1]; char initial[2] int ident;};

Structure Definition

struct personnel_rect employee;

Direct Selection Operator (.)

strcpy( employee.last, "shmoe" );strcpy( employee.first, "joe" );strcpy( employee.initial, "q" );employee.ident = 100;

Structures

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...l%20Work/AdvancedC/Binders/020Review/110Structures.html [3/29/2008 10:01:02 AM]

Page 4: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Structures

Structures and typedeftypedef struct personnel_rec{ char last[51]; char first[51]; char initial[2]; int ident;} EMP_REC_t, *EMP_REC_p_t;

static void print_employee( EMP_REC_p_t emp);

int main( int argc, char **argv ){ EMP_REC_t employee; . . . print_employee( &employee ); . . .}

static voidprint_employee( EMP_REC_p_t emp ){ printf( "%s, %s %s: %d\n", emp->last, emp->first, emp->initial, emp->ident );}

Structures

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...k/AdvancedC/Binders/020Review/115StructuresTypedef.html [3/29/2008 10:01:02 AM]

Page 5: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Structures

Pointers to Structures

static void print_employee( struct personnel_rec *emp);

int main( int argc, char **argv ){ struct personnel_rec employee; . . . print_employee( &employee ); . . .}

Indirect Selection Operator (->)

static voidprint_employee( struct personnel_rec *emp ){ printf( "%s, %s %s: %d\n", emp->last, emp->first, emp->initial, emp->ident, );}

Structures

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...dvancedC/Binders/020Review/120PointersToStructures.html [3/29/2008 10:01:03 AM]

Page 6: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Pointers

PointersDefinition:

The address of an object of a particular type, or a variable which may be used to represent such an address.

typedef

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2...k/AdvancedC/Binders/020Review/200PointersDefinition.html [3/29/2008 10:01:03 AM]

Page 7: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

void Pointers

void Pointersvoid pointers (also called generic pointers) can hold any address except the address of a function.

int inx = 376;double dnx = 3.14;void *ptr = &inx;. . .printf( "%d\n", *(int *)ptr );ptr = &dnx;printf( "%lf\n", *(double *)ptr );

void pointers

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...0Work/AdvancedC/Binders/020Review/210VoidPointers.html [3/29/2008 10:01:03 AM]

Page 8: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

NULL Pointers

NULL PointersAny pointer variable may be given and tested for a value of NULL.

Important: NULL is not necessarily equivalent to 0.

void *ptr = NULL;. . .if ( ptr != NULL ) printf( "%d\n", *(int *)ptr );else printf( "eh?" );

NULL pointers

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...20Work/AdvancedC/Binders/020Review/220NullPointers.html [3/29/2008 10:01:03 AM]

Page 9: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Pointer Operations

Pointer OperationsNon-void pointer variables may be incremented and decremented by an integer value:

int iarr[] = { 10, 20, 30, 40 };int inx = 0;int *iptr = iarr;

for ( inx = 0 ; inx < 2 ; ++inx, iptr += 2 ) printf( "%d ", *iptr );

Pointer Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...k/AdvancedC/Binders/020Review/230PointerOperations.html [3/29/2008 10:01:03 AM]

Page 10: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Pointer Operations

Pointer OperationsNon-void pointer variables pointer to the same array (or the first address after the array) may be compared:

int iarr[] = { 10, 20, 30, 40 };int *end = iarr + 4;int *iptr = iarr;

for ( iptr = iarr ; iptr < end ; ++iptr ) printf( "%d ", *iptr );

(alternatively)

for ( iptr = iarr ; iptr < &iarr[4] ; ++iptr ) printf( "%d ", *iptr );

or subtracted:

int iarr[] = { 10, 20, 30, 40 };int *ptr1 = iarr + 1;int *ptr2 = iarr + 3;ptrdiff_t diff = ptr2 - ptr1;

for ( iptr = iarr ; iptr < end ; ++iptr ) printf( "%d ", *iptr );

Pointer Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...k/AdvancedC/Binders/020Review/240PointerOperations.html [3/29/2008 10:01:04 AM]

Page 11: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Pointer Arithmetic

Pointer Arithmeticint iarr[] = { 10, 20, 30, 40, 50, 60, 70 };int *iptr = iarr;

iptr points to iarr[0] (&iarr[0])

*iptr refers to the contents of iarr[0] (10)

(iptr + 1) points to iarr[1] (&iarr[1])

*(iptr + 1) refers to the contents of iarr[1] (20)

(iptr + 3) points to iarr[3] (&iarr[3])

*(iptr + 3) refers to the contents of iarr[3] (40)

Pointer Arithmetic

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...k/AdvancedC/Binders/020Review/250PointerArithmetic.html [3/29/2008 10:01:04 AM]

Page 12: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Pointer Arithmetic

Pointer Arithmeticint iarr[] = { 10, 20, 30, 40, 50, 60, 70 };int *iptr = &iarr[3];

iptr points to iarr[3]

iptr + 2 points to iarr[5]

iptr - 2 points to iarr[1]

iptr = iptr + 1 iptr points to iarr[4];

iptr += 1 iptr points to iarr[5];

++iptr iptr points to iarr[6];

iptr++ iptr points to iarr[7];

inx = *ptr++ inx = *ptr then increment ptr

inx = *++ptr increment ptr then inx = *ptr

inx = *ptr-- inx = *ptr then decrement ptr

inx = *--ptr decrement ptr then inx = *ptr

Pointer Arithmetic

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...k/AdvancedC/Binders/020Review/260PointerArithmetic.html [3/29/2008 10:01:04 AM]

Page 13: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Strings

Strings● Strings are not intrinsic in C.

● A string is an array of characters the last of which is the nul

character:

char str1[] = { 's', 'p', 'o', 't', '\000' };char str2[] = "spot";char str3[5];

str3[0] = 's';str3[1] = 'p';str3[2] = 'o';str3[3] = 't';str3[4] = '\000';

● The nul character is logically different from the NULL pointer.

Strings

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/310Strings.html [3/29/2008 10:01:04 AM]

Page 14: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Strings

String LiteralsA string literal (or string constant) is an unnamed character array with an address and a length:

/* COPIES the 6 element array "sally" into the * 6 element array str1*/char str1[] = "sally";

/* Puts the ADDRESS of the 5 element array * "jane" into the variable str2*/char *str2 = "jane";

/* Changes the array str1 from sally to tally; * does NOT change the literal "sally"*/str1[0] = 't';

/*Equivalent to str1[0] = 't' */*str1 = 't';

/* UNDEFINED BEHAVIOR; * Attempts to change the literal "jane" to "mane" */*str2 = 'm';

Strings

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/320Strings.html [3/29/2008 10:01:05 AM]

Page 15: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Strings

String OperationsSince strings are not intrinsic, copy, comparison and other operations must be performed character-by-character:

int main( char **argv, int argc ){ char str1[] = ... ; char str2[] = ... ; int result = 0;

result = my_strcmp( str1, str2 ); if ( result == 0 ) puts( "strings are equal" ); else if ( result < 0 ) puts( "str1 less than str2" ); else if ( result > 0 ) puts( "str1 greater than str2" ); else abort();

return 0;}

static int my_strcmp( const char *strA, const char *strB ){ int comp = 0;

do { comp = *strA - *strB++; } while ( comp == 0 && *strA++ != '\000' );

return comp;}

Strings

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...rk/AdvancedC/Binders/020Review/330StringOperations.html [3/29/2008 10:01:05 AM]

Page 16: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Strings

String Operations (continued)static char *my_strcpy( char *strA, const char *strB );static int my_strlen( const char *str );int main( char **argv, int argc ){ char str1[] = "Dick threw the ball to Sally"; char str2[101] = "a"; int len = 0;

my_strcpy( str2, str1 ); len = my_strlen( str2 ); printf( "%d/%s\n", len, str2 );

return 0;}

static char *my_strcpy( char *strA, const char *strB ){ int comp = 0;

do { *strA = *strB++; } while ( *strA++ != '\000' );

return strA;}

static int my_strlen( const char *str ){ int len = 0;

while ( *str++ != '\000' ) ++len;

return len;}

Strings

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...rk/AdvancedC/Binders/020Review/340StringOperations.html [3/29/2008 10:01:05 AM]

Page 17: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Strings

"Safe" String CopiesTo avoid buffer overflows use strncpy instead of strcpy:

char *godog = "Hello! Do you like my hat?";char str[20];unsigned len = sizeof(str);

strncpy( str, godog, len );str[len - 1] = '\000';

WARNING: strncpy does not necessarily properly terminate the copy; consider:

#define STRNCPY( to, fr, len ) \ (strncpy( (to), (fr), (len) ), (to)[(len) - 1] = '\000', (to))

Strings

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/350Strncpy.html [3/29/2008 10:01:06 AM]

Page 18: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsingsscanf

int sscanf( char *src, const char *fmt, ... ); See: H&S, Sec. 15.8

src: string to parse fmt: format string additional arguments: pointers to storage returns: number of fields parsed

str = "name smith id 6"

char nameTag[81];char name[81];char identTag[81];int ident = 0;

sscanf( str, "%s %s %s %d", nameTag, name, identTag, &ident );printf( "%s/%s\n%s/%d\n", nameTag, name, identTag, ident );

name/smith id/6

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/360Sscanf.html [3/29/2008 10:01:06 AM]

Page 19: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsingsscanf

The assignment suppression flag: *

str = "name smith id 6"

char name[81];int ident = 0;

sscanf( str, "%*s %s %*s %d", name, &ident );printf( "%s/%d\n", name, ident );

smith/6

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/370Sscanf.html [3/29/2008 10:01:06 AM]

Page 20: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsingsscanf

Simple error detection:

char field2[81];char field3[81];int field4 = 0;

char junk[2];int count = 0;

count = sscanf( str, "%s %s %s %d %s %1s", field1, field2, field3, &field4, junk );if ( count < 4 ) printf( "too few fields (%d)\n", count );else if ( count > 4 ) printf( "too many fields (%d)\n", count );else printf( "%s/%d\n", field2, field4 );

str = "name smith id 6" smith/6 str = "name smith id" too few fields (3) str = "name smith id 6 eh" too many fields (5) str = "name smith id 6eh" too many fields (5) /* !!! */ str = "name smith id eh" too few fields (3) /* !!! */

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/380Sscanf.html [3/29/2008 10:01:06 AM]

Page 21: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsingsscanf

sscanf is primarily useful with strictly formatted record-like strings.

Message Format:

NNNNNYYYYMMDDHHMMSSOOO - data -

Bytes 00 - 04: Message number, numeric, 0-padded Bytes 05 - 18: Timestamp, numeric, 0-padded, year-month-day-hours-minutes-seconds Bytes 19 - 21: Operation, alphanumeric, blank-padded Bytes 22 - 79: Data, alphanumeric, blank-padded

char *msg... int count = 0;int msg_num = 0;int year = 0;int month = 0;int day = 0;int hours = 0;int mins = 0;int secs = 0;char oper[4];char data[59];

count = sscanf( msg, "%5d%4d%2d%2d%2d%2d%2d%3s%58s", &msg_num, &year, &month, &day, &hours, &mins, &secs, oper, data );if ( count != 9 ) process_error( ... );else process_msg( ... );

file:///C|/Documents%20and%20Settings/Jack%20Straub/...ol%20Work/AdvancedC/Binders/020Review/390sscanf.html (1 of 2) [3/29/2008 10:01:07 AM]

Page 22: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/...ol%20Work/AdvancedC/Binders/020Review/390sscanf.html (2 of 2) [3/29/2008 10:01:07 AM]

Page 23: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsingstrtok

char *strtok( char *src, const char *delims ); See: H&S, Sec. 13.7 See also the strtok() examples in the Sample Code pages.

src: string to tokenize delims: set of characters that delimit tokens

1. Call strtok passing the string to tokenize and set of delimiters. strtok will save the string and return the first token (or NULL if no token found).

2. Call strtok repeatedly passing NULL and set of delimiters, which may be different from one call to the next. strtok will return successive tokens, or NULL when no tokens are left.

3. The original string is destroyed.

src[] = "Go! Go dog, go!"char *delims = "!,. ";char *token = strtok( src, delims );while ( token != NULL ){ printf( "%s\n", token ); token = strtok( NULL, delims );}

Go Go dog go

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/410strtok.html [3/29/2008 10:01:07 AM]

Page 24: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String Parsingstrtok

src[] = "2007/01/29/4/57/23" year/month/day/hours/minutes/seconds

#define NUM_FIELDS (6)char *tokens[NUM_FIELDS + 1] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };int inx = 0;

tokens[0] = strtok( src, "/" );while ( inx <= NUM_FIELDS && tokens[inx] != NULL ) tokens[++inx] = strtok( NULL, "/" );if ( tokens[NUM_FIELDS-1] == NULL ) puts( "too few fields" );else if ( tokens[NUM_FIELDS] != NULL ) puts( "too many fields" );else printf( "%s-%s-%s %s:%s:%s\n", tokens[2], /* day */ tokens[1], /* month */ tokens[0], /* year */ tokens[3], /* hours */ tokens[4], /* mins */ tokens[5] /* secs */ );

29-01-2007 4:57:23

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/420strtok.html [3/29/2008 10:01:07 AM]

Page 25: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String ParsingString-to-binary conversions

See H&S, Sec. 16.4

string-to-double: double strtod( const char *str, char **ptr );

string-to-long, string-to-unsigned-long: long strtol( const char *str, char **ptr, int base ); unsigned long strtoul( const char *str, char **ptr, int base );

str: string to convert; may contain leading white space.

ptr: a pointer to a pointer; may be NULL. If not NULL, used to return to the caller a pointer of the first unconverted character in the string. This may be used to validate the conversion.

base: the base to use for the conversion; may be 0.

Returns:

1. Converted number, if conversion is possible; 2. Pointer to first unconverted character (via ptr, if non-NULL); 3. Sets errno if conversion is impossible, or if overflow or underflow occur.

char *end = NULL;long num = 0;

errno = 0;num = strtol( str, &end, 0 );if ( errno != 0 ) printf( "Error; errno = %d, %s\n", errno, strerror( errno ) );else if ( *end != '\000' ) printf( "Error; conversion terminated at \"%c\"\n", *end );else printf( "Conversion successful: %d\n", num );

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/430strtox.html [3/29/2008 10:01:08 AM]

Page 26: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String ParsingString-to-binary conversions

str = "2007" Conversion successful: 2007

str = " 2007" Conversion successful: 2007

str = "t2007" Error; conversion terminated at "t"

str = "2007 " Error; conversion terminated at " "

str = "2007x0" Error; conversion terminated at "x"

str = "20079999999999" Error; errno = 34, Numerical result out of range

str = "02007" Conversion successful: 1031

str = "02008" Error; conversion terminated at "8"

str = "0x2008" Conversion successful: 8200

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/440strtox.html [3/29/2008 10:01:08 AM]

Page 27: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String ParsingString-to-binary conversions

char *end = NULL;double num = 0;

errno = 0;num = strtod( str, &end );if ( errno != 0 ) printf( "Error; errno = %d, %s\n", errno, strerror( errno ) );else if ( *end != '\000' ) printf( "Error; conversion terminated at \"%c\"\n", *end );else printf( "Conversion successful: %lf\n", num );

str = "2008" Conversion successful: 2008.000000

str = "200t8" Error; conversion terminated at "t"

str = "-2e3" Conversion successful: -2000.000000

str = "-2e-3" Conversion successful: -0.002000

str = "-2e1000" Error; errno = 34, Numerical result out of range

str = "-2e-1000" Error; errno = 34, Numerical result out of range

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/450strtox.html [3/29/2008 10:01:08 AM]

Page 28: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

String ParsingString-to-binary conversions

char *temp = str + strlen( str ) - 1;

while ( temp > str && isspace( *temp ) ) *temp-- = '\000';

temp = str;while ( *temp != '\000' ){ long num = strtol( temp, &temp, 0 ); printf( "%d\n", num );}

str = " 100 200 300 400 500 " 100 200 300 400 500

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/460strtox.html [3/29/2008 10:01:08 AM]

Page 29: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

String Parsing

X">

String ParsingString-to-binary conversions

Note: atoi, atof and atol are non-deterministic; i.e., when the target string cannot be converted their behavior is undefined.

Don't use them.

String Parsing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...hool%20Work/AdvancedC/Binders/020Review/470strtox.html [3/29/2008 10:01:09 AM]

Page 30: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Typedef

typedef ● typedef as-type new-type;

typedef int IDENT_t;typedef struct personnel_rec EMP_REC_t;

● typedef as-type *new-pointer-type;

typedef int *IDENT_p_t;typedef struct personnel_rec *EMP_REC_p_t;

● typedef as-type new-type, new-type, ...;

typedef int EMP_ID_t, SEQ_NUM_t, YEAR_t, MONTH_t;

● typedef as-type new-type[num]

typedef char NAME_t[NAME_LEN + 1];typedef char INITIAL_t[2];

typedef

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/510Typedef.html [3/29/2008 10:01:09 AM]

Page 31: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

typedef

typedeftypedef struct personnel_rec{ NAME_t last; NAME_t first; INITIAL_t initial; EMP_ID_t ident;} EMP_REC_t, *EMP_REC_p_t;

static void print_employee( EMP_REC_p_t emp);

int main( int argc, char **argv ){ EMP_REC_t employee; . . . print_employee( &employee ); . . .}

static voidprint_employee( EMP_REC_p_t emp ){ printf( "%s, %s %s: %d\n", emp->last, emp->first, emp->initial, emp->ident );}

typedef

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/520Typedef.html [3/29/2008 10:01:09 AM]

Page 32: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Testing

TestingConditional Preprocessing

#ifdef ENABLE_LOGGING#define LOG( file, str ) (write_log( (file), (str)))#else#define LOG( file, str ) ((void)0)#endif

#ifndef NDEBUG#define ASSERT_WARN( expr ) \ (!(expr) ? assert_warn( __FILE__, __LINE__, #expr) : ((void)0))#else#define ASSERT_WARN( expr ) ((void)0)#endif

#if DEBUG_LEVEL > 3 && errno != 0 abort();#elif DEBUG_LEVEL > 2 && errno != 0 fprintf( stderr, "error at step 5" );#else ;#endif

Testing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2...ncedC/Binders/020Review/610ConditionalPreprocessing.html [3/29/2008 10:01:09 AM]

Page 33: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Testing

TestingLevels of Testing

Unit Testing Testing an individual algorithm, function, module (a set of related functions) or other unit of code such as a loop.

Integration Testing Testing the interface between modules.

System Testing Testing the system against end user requirements, including performance testing.

Approaches to Testing

Whitebox Testing Testing that incorporates a detailed knowledge of the code being tested; testing individual code paths.

Blackbox Testing Testing a system or unit without detailed assumptions about the underlying code.

Testing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/710Testing.html [3/29/2008 10:01:10 AM]

Page 34: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Testing

TestingTest Cases

A test case is typically a brief scenario designed to validate a software unit.

/* -1 <= parm < 1 */double funkX( double parm );

Does funkX return the correct value when:

● Test Case 100: parm = -1 ● Test Case 120: parm = .9999999 ● Test Case 130: parm = 0 ● Test Case 140: parm = -.3 ● Test Case 150: parm = .6

and possibly

● Test Case 200: parm = -2 ● Test Case 210: parm = 1

Test Plan

● In What order will test cases be executed? ● How much time will be required to execute all test cases? ● What resources (computers, testers, etc.) will be required and for

how long? ● If test case X fails, which other test cases may or may not be

executed?

Testing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/720Testing.html [3/29/2008 10:01:10 AM]

Page 35: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Testing

TestingTest Tools

● Memory validation: Purify, Microsoft Developer Studio, BoundsChecker, ccmalloc, Valgrind, et al.

● Test case management ● Assertions ● Conditional preprocessing

Testing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...ool%20Work/AdvancedC/Binders/020Review/730Testing.html [3/29/2008 10:01:10 AM]

Page 36: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

Testing

TestingAssertions

#include <assert.h>/* -1 <= parm < 1 */double funkX( double parm );{ assert( parm >= -1 ); assert( parm < 1 ); . . .

If NDEBUG is not defined... and assertion is not true... then:

● file name and line number of assertion will print to stderr; ● program will abort.

Testing

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...%20Work/AdvancedC/Binders/020Review/740Assertions.html [3/29/2008 10:01:10 AM]

Page 37: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsH&S Chapter 15

Topics

1. FILE Data Type 2. Streams 3. Operations 4. Mode 5. Binary vs. Text Streams 6. Binary File Layout

File Operations

0:01:11 AM]file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2...vancedC/Binders/030FileOperations/110FileOperations.html [3/29/2008 1

Page 38: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsFILE Data Type

● Opaque structure that encapsulates information about a file, such as:

�❍ Whether or not an error has occurred. �❍ The current position within the file for reading and/or writing. �❍ Whether or not end-of-file (EOF) has been encountered.

● A pointer to a FILE structure (FILE*) is obtained by calling fopen.

● Most file operations are performed using a FILE*.

● When no longer needed, a FILE structure must be disposed by calling fclose.

FILE *file = fopen( ... );. . .fclose( file );

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...dvancedC/Binders/030FileOperations/120FileDataType.html [3/29/2008 10:01:11 AM]

Page 39: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsStreams

● The C Standard Library file I/O functions view a file as a sequence of bytes called a stream.

● A stream may be associated with a physical file, typically stored on a disk, or a virtual file, such as a keyboard or printer.

● Streams may consist of text or binary data.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/030FileOperations/130Streams.html [3/29/2008 10:01:11 AM]

Page 40: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText Streams

● A text stream consists of characters (typically printable characters) divided into lines.

● Each line in a text stream is terminated by a newline character (\n) which is considered part of the line.

● Lines may consist of up to at least 254 characters.

● Text streams are generally considered portable.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2.../AdvancedC/Binders/030FileOperations/140TextStreams.html [3/29/2008 10:01:11 AM]

Page 41: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsBinary Streams

● A binary stream consists of any sequence of bytes.

● Binary streams are useful for recording data in an easily recoverable format.

● Binary streams should generally not be considered portable.

● A C implementation may choose to view binary files in the same way as text files; for maximum portability of your code, always assume that they are handled differently (see fopen, below).

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2...dvancedC/Binders/030FileOperations/150BinaryStreams.html [3/29/2008 10:01:12 AM]

Page 42: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsFILE *fopen( const char *filename, const char *mode );

Prepares a file for reading and/or writing. The maximum number of files that you may have open is determined by the macro FOPEN_MAX, which must be at least 8 (presently, on my XP system it is 20, and 16 on my LINUX system).

filename The name of the file to open. The format of the name is dependent on your operating system.

mode Specifies whether the target file is text or binary, and whether it is to be opened for reading and/or writing (see below).

Returns: A pointer to a FILE structure, or NULL if the operation fails.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...0Work/AdvancedC/Binders/030FileOperations/160fopen.html [3/29/2008 10:01:12 AM]

Page 43: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsMode

"r" Opens an existing text file for reading.

"w" Creates a new text file for writing. If a file by the same name already exists its contents are lost.

"a" Opens a text file for writing. If the file does not already exist it is created; if the file exists its contents are preserved and new data is added to the end of the file.

"r+" Opens an existing text file for reading and writing.

"w+" Creates a new text file for reading and writing. If a file by the same name already exists its contents are lost.

"a+" Opens a text file for reading and writing. If the file does not already exist it is created; if the file exists its contents are preserved and reading and writing begins at the end of the file.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...0Work/AdvancedC/Binders/030FileOperations/170Mode.html [3/29/2008 10:01:12 AM]

Page 44: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsMode

● "rb" ● "wb" ● "ab" ● "rb+" ● "wb+" ● "ab+"

These are the same as "r", "w", "a", etc., except that the target file is binary rather than text.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My...0Work/AdvancedC/Binders/030FileOperations/180Mode.html [3/29/2008 10:01:12 AM]

Page 45: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsint fclose( FILE *file );

Closes a previously opened file.

file The file to close.

Returns: 0 if successful, EOF if an error occurs.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/190fclose.html [3/29/2008 10:01:13 AM]

Page 46: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationserrno

When most file operations fail a non-0 value is stored in errno; the specific value is generally implementation defined. If the operation succeeds errno is unchanged.

To obtain a string that describes an error code use strerror.

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <errno.h>

int main( int argc, char **argv ){ FILE *file = NULL;

errno = 0; if ( (file = fopen( "george.txt", "r" )) == NULL ) fprintf( stderr, "Open file error: %d, \"%s\"\n", errno, strerror( errno ) ); else process( file );

if ( file != NULL ) fclose( file );

return EXIT_SUCCESS;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...0Work/AdvancedC/Binders/030FileOperations/200Errno.html [3/29/2008 10:01:13 AM]

Page 47: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsFILE *freopen( const char *name, const char *mode, FILE *stream );

Closes a previously opened stream and opens a new stream associated with the original file structure (FILE *);

name The file to be associated with the new stream.

mode The mode of the new stream (see fopen).

stream The stream to close.

Returns: stream if successful, NULL if an error occurrs.

● First closes stream; any error that occurs is ignored.

● Opens the new stream and associates it with the original FILE structure.

● Mainly used for redirecting stdin, stdout and stderr.

#include <stdio.h>#include <stdlib.h>

int main( int argc, char **argv ){ FILE *file = fopen( "dick.txt", "w" );

if ( file == NULL ) fputs( "\"dick.txt\" open failure", stderr ); else { fputs( "oranges\n", file ); // Note: should check for error fputs( "apples\n", file ); // Note: should check for error if ( freopen( "jane.txt", "w", file ) == NULL ) fputs( "\"dick.txt\" open failure", stderr ); else { fputs( "pears\n", file ); // Note: should check for error fputs( "plums\n", file ); // Note: should check for error fclose( file ); // Note: should check for error } }

return EXIT_SUCCESS;}

Jack Straub@farsideofthemoo ~/test/c$ cat dick.txt

file:///C|/Documents%20and%20Settings/Jack%20Straub/M...k/AdvancedC/Binders/030FileOperations/210freopen.html (1 of 2) [3/29/2008 10:01:13 AM]

Page 48: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

orangesapples

Jack Straub@farsideofthemoo ~/test/c$ cat jane.txtpearsplums

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/M...k/AdvancedC/Binders/030FileOperations/210freopen.html (2 of 2) [3/29/2008 10:01:13 AM]

Page 49: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsstdin stdout stderr

● Associated with default input and output devices. ● May be redirected using freopen.

#ifdef NDEBUG if ( freopen( "output_log.txt", "w", stdout ) == NULL ) abort(); if ( freopen( "error_log.txt", "w", stderr ) == NULL ) abort();#endif

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2...k/AdvancedC/Binders/030FileOperations/220StdStreams.html [3/29/2008 10:01:13 AM]

Page 50: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsint fflush( FILE *stream );

Flushes (writes to disk) the buffers of an open stream.

stream The stream to flush.

Returns: 0 if successful, EOF if an error occurrs.

#include <stdio.h>#include <stdlib.h>

static void test( const char *file_name);

int main( int argc, char **argv ){ FILE *file = fopen( "george.txt", "w" ); if ( file == NULL ) abort(); // not the best way to handle I/O failure

fputs( "sandy beaches\n", file ); test( "george.txt" ); fflush( file ); test( "george.txt" );

fclose( file );

return EXIT_SUCCESS;}

static void test( const char *file_name ){ static int count = 0; FILE *file = fopen( file_name, "r" ); char buf[512];

if ( file == NULL ) abort(); // not the best way to handle I/O failure

fgets( buf, sizeof(buf), file ); printf( "(%d) -- %s\n", ++count, buf );

fclose( file );

file:///C|/Documents%20and%20Settings/Jack%20Straub/M...rk/AdvancedC/Binders/030FileOperations/230fflush.html (1 of 2) [3/29/2008 10:01:14 AM]

Page 51: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

}

(1) --(2) -- sandy beaches

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/M...rk/AdvancedC/Binders/030FileOperations/230fflush.html (2 of 2) [3/29/2008 10:01:14 AM]

Page 52: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationslong ftell( FILE *stream );

Calculates the position used for reading and writing in the target stream.

stream The stream to interrogate.

Returns: Read/write position or -1 on failure.

● For binary files, the position will be the number of bytes preceding the current position.

● For text files the position is implementation-dependent.

● The position may always be used as the second argument to fseek.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%2...20Work/AdvancedC/Binders/030FileOperations/240ftell.html [3/29/2008 10:01:14 AM]

Page 53: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsint fseek( FILE *stream, long offset, int from );

Repositions the target stream for reading and writing.

stream The stream to reposition.

offset Offset from from to establish the new position.

from Referent to use with offset to establish the new position. May be one of the following:

�❍ SEEK_SET - calculate offset from the beginning of the file. �❍ SEEK_CUR - calculate offset from the current position. �❍ SEEK_END - calculate offset from the end of the file.

Returns: 0 for success, non-0 for failure.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...0Work/AdvancedC/Binders/030FileOperations/250fseek.html [3/29/2008 10:01:14 AM]

Page 54: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfseek, ftell Example

Given: a binary file, seek_test.bin, that consists of sequential records created with fwrite using this structure:

typedef struct rec_s{ char name[26]; int id;} REC_t, *REC_p_t;

(continued...)

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/030FileOperations/260Example.html [3/29/2008 10:01:15 AM]

Page 55: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfseek, ftell Example (continued)

The program find_rec is used to locate records by sequence number within the file, e.g.

> find_rec 3

int main( int argc, char **argv ){ int rcode = EXIT_SUCCESS;

if ( argc < 2 ) { fputs( "record number argument required", stderr ); rcode = EXIT_FAILURE; } else { char *end = NULL; long num = 0;

errno = 0; num = strtol( argv[1], &end, 0 ); if ( errno != 0 || *end != '\000' ) { fputs( "record number must be numeric", stderr ); rcode = EXIT_FAILURE; } else if ( !find( num ) ) rcode = EXIT_FAILURE; else rcode = EXIT_SUCCESS; }

return rcode;}

(continued...)

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/030FileOperations/270Example.html [3/29/2008 10:01:15 AM]

Page 56: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfseek, ftell Example (continued)

This function locates and prints the record. It returns non-zero if successful, 0 if:

● An I/O failure occurs; ● The record number is out of range.

static int find( long num ){ int rcode = 0; long count = 0; REC_t rec;

FILE *file = fopen( "seek_test.bin", "rb" ); if ( file == NULL ) fputs( "file open failure", stderr ); else { fseek( file, 0, SEEK_END ); /* number of bytes in the file divided by size of record * equals number of records in the file. */ count = ftell( file ) / sizeof(rec); if ( num < 0 || num >= count ) fputs( "record number out of range", stderr ); else { fseek( file, num * sizeof(rec), SEEK_SET ); if ( fread( &rec, sizeof(rec), 1, file ) < 1 ) fputs( "file I/O error", stderr ); else { rcode = 1; printf( "%s: %d\n", rec.name, rec.id ); } } }

return rcode;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...ork/AdvancedC/Binders/030FileOperations/280Example.html [3/29/2008 10:01:15 AM]

Page 57: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsint feof( FILE *stream ); Indicates whether end-of-file has been detected when reading from stream. Returns 0 if end-of-file has not been detected, non-0 if end-of-file has been detected.

int ferror( FILE *stream ); Indicates whether an error has been detected when operating on stream. Returns 0 if an error has not been detected, non-0 if an error has been detected.

void rewind( FILE *stream ); Equivalent to (void)fseek( stream, 0, SEEK_SET ).

int rename( const char *oldname, const char *newname ); int remove( const char *name ); Rename or remove a file, respectively. The meaning of remove is implementation defined. If name or oldname are nonexistent files; or if newname exists; or if any of the target files are open; then the result of the operation is implementation defined. These functions return 0 if successful, non-0 if unsuccessful.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...20Work/AdvancedC/Binders/030FileOperations/290Misc.html [3/29/2008 10:01:15 AM]

Page 58: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText I/O

int fgetc( FILE *stream ); int getc( FILE *stream );

Read one character from a stream.

stream The stream to read from.

Return: The character read; or EOF if the end of the stream is encountered; or EOF if an error is encountered.

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t nextchar( FILE *str, char *out ){ FSTATUS_e_t status = FSUCCESS; int var = 0;

errno = 0; if ( (var = getc( str )) != EOF ) *out = (char)var; else if ( feof( str ) ) status = FDONE; else { status = FERROR; log_error( "getc failure", errno ); }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/300TextIO.html [3/29/2008 10:01:16 AM]

Page 59: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText I/O

char *fgets( char *buf, int size, FILE *stream );

Read a line from a stream into buf; up to size - 1 characters are read and the resultant string is null-terminated. The newline at the end of the line is retained.

buf The buffer to read into.

buf The size of the buffer.

stream The stream to read from.

Returns: buf; or NULL if the end of the stream is encountered; or NULL if an error is encountered.

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t nextline( FILE *str, char *out, size_t size ){ FSTATUS_e_t status = FSUCCESS; int var = 0;

errno = 0; if ( fgets( out, (int)size, str ) == out ) ; else if ( feof( str ) ) status = FDONE; else { status = FERROR; log_error( "fgets failure", errno ); }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/310TextIO.html [3/29/2008 10:01:16 AM]

Page 60: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText I/O

int fscanf( FILE *stream, const char *format, ... );

See H&S, Section 15.8.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/320TextIO.html [3/29/2008 10:01:16 AM]

Page 61: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText I/O

int fputc( int cval, FILE *stream ); int putc( int cval, FILE *stream );

Write one character to a stream.

cval The character to write.

stream The stream to write to.

Return: The character written (cval); or EOF if an error is encountered.

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t putcval( FILE *str, char cval ){ FSTATUS_e_t status = FSUCCESS;

errno = 0; if ( putc( cval, str ) == EOF ) { status = FERROR; log_error( "putc failure", errno ); }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/330TextIO.html [3/29/2008 10:01:16 AM]

Page 62: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText I/O

int fputs( char *text, FILE *stream );

Writes text to a stream.

text The text to write.

stream The stream to write to.

Returns: A non-negative value if successful; or EOF if an error is encountered.

Remember: Every line in a text file must be terminated with a newline, and fputs does not do this for you.

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t putstr( FILE *str, const char *text ){ FSTATUS_e_t status = FSUCCESS;

errno = 0; if ( fputs( text, str ) == EOF ) { status = FERROR; log_error( "fputs failure", errno ); }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/340TextIO.html [3/29/2008 10:01:17 AM]

Page 63: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsText I/O

int fprintf( FILE *stream, const char *format, ... );

See H&S, Section 15.11.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...Work/AdvancedC/Binders/030FileOperations/350TextIO.html [3/29/2008 10:01:17 AM]

Page 64: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsBinary I/O

size_t fwrite( const void *ptr, size_t el_size, size_t count, FILE *str );

Writes count records to the binary stream str.

ptr Pointer to an array of some type (usually a struct).

el_size Size of an element in the array.

count Number of elements in the array.

str Stream to write to.

Returns: count; or a number less than count if an error occurs.

Note: If either count or el_size is 0, no operation will be attempted and 0 will be returned.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...rk/AdvancedC/Binders/030FileOperations/360BinaryIO.html [3/29/2008 10:01:17 AM]

Page 65: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfwrite Example 1

#include <stdio.h>#include <stdlib.h>#include <errno.h>

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t putrecs( FILE *str, const void *recs, size_t size, size_t count);

typedef struct record_s{ int ident; char name[81];} RECORD_t, RECORD_p_t;

int main( int argc, char *argv ){ int rcode = EXIT_SUCCESS; FILE *file = fopen( "jane.bin", "wb" ); RECORD_t recs[] = { { 1, "dick" }, { 3, "sally" }, { 2, "jane" }, { 4, "spot" } };

// Not the best way to handle an I/O error. if ( file == NULL ) abort();

if ( putrecs( file, recs, sizeof(RECORD_t), 4 ) != FSUCCESS ) rcode = EXIT_FAILURE;

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/370BinaryIO.html (1 of 2) [3/29/2008 10:01:17 AM]

Page 66: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

fclose( file );

return rcode;}

static FSTATUS_e_tputrecs( FILE *str, const void *recs, size_t size, size_t count ){ FSTATUS_e_t status = FSUCCESS;

errno = 0; if ( fwrite( recs, size, count, str ) == count ) ; else if ( size == 0 ) ; else { status = FERROR; log_error( "fwrite failure", errno ); }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/370BinaryIO.html (2 of 2) [3/29/2008 10:01:18 AM]

Page 67: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfwrite Example 2

#include <stdio.h>#include <stdlib.h>#include <errno.h>

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t putrecs( FILE *str, const void *recs, size_t size, size_t count);

typedef struct record_s{ int ident; char name[81];} RECORD_t, RECORD_p_t;

int main( int argc, char *argv ){ int rcode = EXIT_SUCCESS; FILE *file = fopen( "jane2.bin", "wb" ); RECORD_t rec[] = { 1, "dick" };

// Not the best way to handle an I/O error. if ( file == NULL ) abort();

if ( putrecs( file, &rec, sizeof(RECORD_t), 1 ) != FSUCCESS ) rcode = EXIT_FAILURE;

fclose( file );

return rcode;}

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/380BinaryIO.html (1 of 2) [3/29/2008 10:01:18 AM]

Page 68: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

static FSTATUS_e_tputrecs( FILE *str, const void *recs, size_t size, size_t count ){ FSTATUS_e_t status = FSUCCESS;

errno = 0; if ( fwrite( recs, size, count, str ) == count ) ; else if ( size == 0 ) ; else { status = FERROR; log_error( "fwrite failure", errno ); }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/380BinaryIO.html (2 of 2) [3/29/2008 10:01:18 AM]

Page 69: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File OperationsBinary I/O

size_t fread( const void *ptr, size_t el_size, size_t count, FILE *str );

Reads up to count records from the binary stream str. The actual number of records read may be less than count.

ptr Pointer to an array of some type (usually a struct).

el_size Size of an element in the array.

count Number of elements in the array.

str Stream to read from.

Returns: number of records actually read; or 0 if EOF encountered before any records are read; or 0 if an error occurs.

Note: If either count or el_size is 0, no operation will be attempted and 0 will be returned.

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/My%...rk/AdvancedC/Binders/030FileOperations/390BinaryIO.html [3/29/2008 10:01:18 AM]

Page 70: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfread Example 1

#include <stdio.h>#include <stdlib.h>#include <errno.h>

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t getrecs( FILE *str, void *recs, size_t size, size_t count, size_t *actual /* output */);

typedef struct record_s{ int ident; char name[81];} RECORD_t, RECORD_p_t;

int main( int argc, char *argv ){ int rcode = EXIT_SUCCESS; FILE *file = fopen( "jane.bin", "rb" ); int inx = 0; int count = 0; RECORD_t recs[10];

// Not the best way to handle an I/O error. if ( file == NULL ) abort();

if ( getrecs( file, recs, sizeof(RECORD_t), 10, &count ) != FSUCCESS ) { if ( ferror( file ) ) rcode = EXIT_FAILURE; } else { for ( inx = 0 ; inx < count ; ++inx ) printf( "ID: %d, Name: %s\n", recs[inx].ident, recs[inx].name ); }

fclose( file );

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/400BinaryIO.html (1 of 2) [3/29/2008 10:01:18 AM]

Page 71: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

return rcode;}

static FSTATUS_e_tgetrecs( FILE *str, void *recs, size_t size, size_t count, size_t *actual ){ FSTATUS_e_t status = FSUCCESS; size_t act = 0;

errno = 0; if ( (act = fread( recs, size, count, str )) != 0 ) *actual = act; else if ( feof( str ) ) { *actual = 0; status = FDONE; } else { log_error( "fread failure", errno ); status = FERROR; }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/400BinaryIO.html (2 of 2) [3/29/2008 10:01:18 AM]

Page 72: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

File Operationsfread Example 2

#include <stdio.h>#include <stdlib.h>#include <errno.h>

typedef enum fstatus_e{ FSUCCESS, FDONE, FERROR} FSTATUS_e_t;

static FSTATUS_e_t getrecs( FILE *str, void *recs, size_t size, size_t count, size_t *actual /* output */);

typedef struct record_s{ int ident; char name[81];} RECORD_t, RECORD_p_t;

int main( int argc, char *argv ){ int rcode = EXIT_SUCCESS; FILE *file = fopen( "jane.bin", "rb" ); int inx = 0; int count = 0; FSTATUS_e_t stat = FSUCCESS; RECORD_t rec;

// Not the best way to handle an I/O error. if ( file == NULL ) abort();

stat = getrecs( file, &rec, sizeof(RECORD_t), 1, &count ); while (stat == FSUCCESS ) { printf( "ID: %d, Name: %s\n", rec.ident, rec.name ); stat = getrecs( file, &rec, sizeof(RECORD_t), 1, &count ); }

if ( stat == FERROR ) rcode = EXIT_FAILURE;

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/410BinaryIO.html (1 of 2) [3/29/2008 10:01:19 AM]

Page 73: C Programming: Advancedfaculty.washington.edu/jstraub/advc/bound_slides/sections1-3.pdfPointer Operations Pointer Operations Non-void pointer variables pointer to the same array (or

File Operations

fclose( file );

return rcode;}

static FSTATUS_e_tgetrecs( FILE *str, void *recs, size_t size, size_t count, size_t *actual ){ FSTATUS_e_t status = FSUCCESS; size_t act = 0;

errno = 0; if ( (act = fread( recs, size, count, str )) != 0 ) *actual = act; else if ( feof( str ) ) { *actual = 0; status = FDONE; } else { log_error( "fread failure", errno ); status = FERROR; }

return status;}

File Operations

file:///C|/Documents%20and%20Settings/Jack%20Straub/...AdvancedC/Binders/030FileOperations/410BinaryIO.html (2 of 2) [3/29/2008 10:01:19 AM]