C: How to Program Week 17 2007/June/18 1 Chapter 11 – File Processing • Outline 11.1 11.2 11.3 11.4 11.5 11.6 11.7 11.8 11.9 11.10 Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a Sequential Access File Random Access Files Creating a Randomly Accessed File Writing Data Randomly to a Randomly Accessed File Reading Data Randomly from a Randomly Accessed File Case Study: A Transaction-Processing Program 2 11.1 Introduction • Data files – Can be created, updated, and processed by C programs – Are used for permanent storage of large amounts of data • Storage of data in variables and arrays is only temporary 3 11.2 The Data Hierarchy • Data Hierarchy: – Bit – smallest data item • Value of 0 or 1 – Byte – 8 bits • Used to store a character – Decimal digits, letters, and special symbols – Field – group of characters conveying meaning • Example: your name – Record – group of related fields • Represented by a struct or a class • Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc. 4 11.2 The Data Hierarchy • Data Hierarchy (continued): – File – group of related records • Example: payroll file – Database – group of related files Judy Judy 01001010 1 Green Record Field Byte (ASCII character J) Sally Black Tom Blue Judy Green Iris Orange File Randy Red Bit Fig. 11.1 The data hierarchy 5 11.2 The Data Hierarchy • Data files – Record key • Identifies a record to facilitate the retrieval of specific records from a file – Sequential file • Records typically sorted by key 6 11.3 Files and Streams • C views each file as a sequence of bytes – File ends with the end-of-file marker • Or, file ends at a specified byte • Stream created when a file is opened – Provide communication channel between files and programs – Opening a file returns a pointer to a FILE structure • Example file pointers: • stdin - standard input (keyboard) • stdout - standard output (screen) • stderr - standard error (screen) 7 11.3 Files and Streams • FILE structure – File descriptor • Index into operating system array called the open file table – File Control Block (FCB) • Found in every array element, system uses it to administer the file 8 11.3 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 – fputs • Writes a line to a file – fscanf / fprintf • File processing equivalents of scanf and printf 9 /* Fig. 11.3: fig11_03.c Create a sequential file */ #include <stdio.h> int main() { int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */ FILE *cfPtr; /* cfPtr = clients.dat file pointer */ /* fopen opens file. Exit program if unable to create file */ if ( ( cfPtr = fopen( "clients.dat", "w" ) ) == NULL ) { printf( "File could not be opened\n" ); } /* end if */ else { printf( "Enter the account, name, and balance.\n" ); printf( "Enter EOF to end input.\n" ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); 10 /* write account, name and balance into file with fprintf */ while ( !feof( stdin ) ) { fprintf( cfPtr, "%d %s %.2f\n", account, name, balance ); printf( "? " ); scanf( "%d%s%lf", &account, name, &balance ); } /* end while */ fclose( cfPtr ); /* fclose closes file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ Enter Enter ? 100 ? 200 ? 300 ? 400 ? 500 ? ^Z the account, name, and balance. EOF to end input. Jones 24.98 Doe 345.67 White 0.00 Stone -42.16 Rich 224.62 11 11.4 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 *cfPtr; • Creates a FILE pointer called cfPtr – cfPtr = fopen("clients.dat", "w"); • Function fopen returns a FILE pointer to file specified • Takes two arguments – file to open and file open mode • If open fails, NULL returned 12 11.4 Creating a Sequential Access File Computer system Key combination UNIX systems <return> <ctrl> d IBM PC and compatibles Macintosh <ctrl> z <ctrl> d Fig. 11.4 End-of-file key combinations for various popular computer systems. – Opening an existing file for writing ( “w” ) when, in fact, the user wants to preserve the file discards the contents of the file without warning. – Forgetting to open a file before attempting to reference it in a program is a logic error. 13 11.4 Creating a Sequential Access File – 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) – 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 14 11.4 Creating a Sequential Access File User has access to this Only the OS has access to this Open File Table 1 cfptr = fopen(“clients.dat”, “w”); fopen returns a pointer to a FILE structure (defined in <stdio.h>) newPtr 2 FILE structure for “clients.dat” contents a descriptor, i.e., a small integer that is an index into the Open File Table 0 1 : : 7 : FCB for “clients.dat” 4 The program calls an 7 3 When the program issues an I/O call the program locates the descriptor (7) in the FILE structure, and uses the descriptor to find the FCB in the Open File Table. OS service that uses data in the FCB to control all input and output to the actual file on the disk. 15 11.4 Creating a Sequential Access File Mode Description r Open a file for reading. w Create a file for writing. If the file already exists, discard the current contents. a Append; open or create a file for writing at end of file. r+ Open a file for update (reading and writing). w+ Create a file for update. If the file already exists, discard the current contents. a+ Append; open or create a file for update; writing is done at the end of the file. rb Open a file for reading in binary mode. wb Create a file for writing in binary mode. If the file already exists, discard the current contents. ab Append; open or create a file for writing at end of file in binary mode. rb+ Open a file for update (reading and writing) in binary mode. wb+ Create a file for update in binary mode. If the file already exists, discard the current contents. ab+ Append; open or create a file for update in binary mode; writing is done at the end of the file. Fig. 11.6 File open modes. 16 11.5 Reading Data from a Sequential Access File • Reading a sequential access file – Create a FILE pointer, link it to the file to read cfPtr = fopen( "clients.dat", "r" ); – Use fscanf to read from the file • Like scanf, except first argument is a FILE pointer fscanf( cfPtr, "%d%s%f", &accounnt, name, &balance ); – 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( cfPtr ) • Repositions file position pointer to beginning of file (byte 0) 17 /* Fig. 11.7: fig11_07.c Reading and printing a sequential file */ #include <stdio.h> int main() { int account; /* account number */ char name[ 30 ]; /* account name */ double balance; /* account balance */ FILE *cfPtr; /* cfPtr = clients.dat file pointer */ /* fopen opens file; exits program if file cannot be opened */ if ( ( cfPtr = fopen( "clients.dat", "r" ) ) == NULL ) { printf( "File could not be opened\n" ); } /* end if */ else { /* read account, name and balance from file */ printf( "%-10s%-13s%s\n", "Account", "Name", "Balance" ); fscanf( cfPtr, "%d%s%lf", &account, name, &balance ); /* while not end of file */ while ( !feof( cfPtr ) ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); fscanf( cfPtr, "%d%s%lf", &account, name, &balance ); } /* end while */ 18 fclose( cfPtr ); /* fclose closes file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ Account 100 200 300 400 500 Name Jones Doe White Stone Rich Balance 24.98 345.67 0.00 -42.16 224.62 – Opening a nonexistent file for reading is an error. 19 /* Fig. 11.8: fig11_08.c Credit inquiry program */ #include <stdio.h> int main() { int request; /* request number */ int account; /* account number */ double balance; /* account balance */ char name[ 30 ]; /* account name */ FILE *cfPtr; /* clients.dat file pointer */ /* fopen opens file; exits program if file cannot be opened */ if ( ( cfPtr = fopen( "clients.dat", "r" ) ) == NULL ) { printf( "File could not be opened\n" ); } /* end if */ else { /* display request options */ printf( "Enter request\n" " 1 - List accounts with zero balances\n" " 2 - List accounts with credit balances\n" " 3 - List accounts with debit balances\n" " 4 - End of run\n? " ); scanf( "%d", &request ); 20 /* process user's request */ while ( request != 4 ) { /* read account, name and balance from file */ fscanf( cfPtr, "%d%s%lf", &account, name, &balance ); switch ( request ) { case 1: printf( "\nAccounts with zero balances:\n" ); /* read file contents (until eof) */ while ( !feof( cfPtr ) ) { if ( balance == 0 ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); } /* end if */ /* read account, name and balance from file */ fscanf( cfPtr, "%d%s%lf", &account, name, &balance ); } /* end while */ break; case 2: printf( "\nAccounts with credit balances:\n" ); 21 /* read file contents (until eof) */ while ( !feof( cfPtr ) ) { if ( balance < 0 ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); } /* end if */ /* read account, name and balance from file */ fscanf( cfPtr, "%d%s%lf", &account, name, &balance ); } /* end while */ break; case 3: printf( "\nAccounts with debit balances:\n" ); /* read file contents (until eof) */ while ( !feof( cfPtr ) ) { if ( balance > 0 ) { printf( "%-10d%-13s%7.2f\n", account, name, balance ); } /* end if */ 22 /* read account, name and balance from file */ fscanf( cfPtr, "%d%s%lf", &account, name, &balance ); } /* end while */ break; } /* end switch */ rewind( cfPtr ); /* return cfPtr to beginning of file */ printf( "\n? " ); scanf( "%d", &request ); } /* end while */ printf( "End of run.\n" ); fclose( cfPtr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ 23 Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run ? 1 Accounts with zero balances: 300 White 0.00 ? 2 Accounts with credit balances: 400 Stone -42.16 ? 3 Accounts with debit balances: 100 Jones 24.98 200 Doe 345.67 500 Rich 224.62 ? 4 End of run. 24 11.5 Reading Data from a Sequential Access File • Sequential access file – Cannot be modified without the risk of destroying other data – Fields can vary in size • Different representation in files and screen than internal representation • 1, 34, -890 are all ints, but have different sizes on disk 300 White 0.00 400 Jones 32.87 (old data in file) If we want to change White's name to Worthington, 300 Worthington 0.00 300 White 0.00 400 Jones 32.87 Data gets overwritten 300 Worthington 0.00ones 32.87 25 11.6 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 100 200 300 400 500 }byte offsets 100 bytes } 100 bytes } 100 bytes } 100 bytes } } } 100 bytes 100 bytes 26 11.6 Random-Access Files • 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 27 11.7 Creating a Randomly Accessed 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 28 11.7 Creating a Randomly Accessed 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 29 /* Fig. 11.11: fig11_11.c Creating a random-access file sequentially */ #include <stdio.h> /* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */ int main() { int i; /* counter used to count from 1-100 */ /* create clientData with default information */ struct clientData blankClient = { 0, "", "", 0.0 }; FILE *cfPtr; /* credit.dat file pointer */ /* fopen opens the file; exits if file cannot be opened */ if ( ( cfPtr = fopen( "credit.dat", "wb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { 30 /* output 100 blank records to file */ for ( i = 1; i <= 100; i++ ) { fwrite( &blankClient, sizeof( struct clientData ), 1, cfPtr ); } /* end for */ fclose ( cfPtr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ 31 11.8 Writing Data Randomly to a Randomly Accessed 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 32 /* Fig. 11.12: fig11_12.c Writing to a random access file */ #include <stdio.h> /* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */ int main() { /* create clientData with default information */ struct clientData Client ; FILE *cfPtr; /* credit.dat file pointer */ /* fopen opens the file; exits if file cannot be opened */ if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { 33 /* require user to specify account number */ printf( "Enter account number" " ( 1 to 100, 0 to end input )\n? " ); scanf( "%d", &client.acctNum ); /* user enters information, which is copied into file */ while ( client.acctNum != 0 ) { /* user enters last name, first name and balance */ printf( "Enter lastname, firstname, balance\n? " ); /* set record lastName, firstName and balance value */ fscanf( stdin, "%s%s%lf", client.lastName, client.firstName, &client.balance ); /* seek position in file to user-specified record */ fseek( cfPtr, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); /* write user-specified information in file */ fwrite( &client, sizeof( struct clientData ), 1, cfPtr ); /* enable user to input another account number */ printf( "Enter account number\n? " ); scanf( "%d", &client.acctNum ); } /* end while */ 34 fclose( cfPtr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ Enter account number ( 1 to 100, 0 to end input ) ? 37 Enter lastname, firstname, balance ? Barker Doug 0.00 Enter account number ? 29 Enter lastname, firstname, balance ? Brown Nancy -24.54 Enter account number ? 96 Enter lastname, firstname, balance ? Stone Sam 34.98 Enter account number ? 88 Enter lastname, firstname, balance ? Smith Dave 258.34 Enter account number ? 33 Enter lastname, firstname, balance ? Dunn Stacey 314.33 Enter account number ? 0 35 11.8 Writing Data Randomly to a Randomly Accessed File 36 11.9 Reading Data Randomly from a Randomly Accessed 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 37 /* Fig. 11.15: fig11_15.c Reading a random access file sequentially */ #include <stdio.h> /* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */ int main() { /* create clientData with default information */ struct clientData blankClient = { 0, "", "", 0.0 }; FILE *cfPtr; /* credit.dat file pointer */ /* fopen opens the file; exits if file cannot be opened */ if ( ( cfPtr = fopen( "credit.dat", "rb" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { 38 printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" ); /* read all records from file (until eof) */ while ( !feof( cfPtr ) ) { fread( &client, sizeof( struct clientData ), 1, cfPtr ); /* display record */ if ( client.acctNum != 0 ) { printf( "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); } /* end if */ } /* end while */ fclose( cfPtr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ 39 Acct 29 33 37 88 96 Last Name Brown Dunn Barker Smith Stone First Name Nancy Stacey Doug Dave Sam Balance -24.54 314.33 0.00 258.34 34.98 40 11.10 Case Study: A Transaction Processing Program • This program – Demonstrates using random access files to achieve instant access processing of a bank’s account information • We will – – – – Update existing accounts Add new accounts Delete accounts Store a formatted listing of all accounts in a text file 41 /* Fig. 11.16: fig11_16.c This program reads a random access file sequentially, updates data already written to the file, creates new data to be placed in the file, and deletes data previously in the file. */ #include <stdio.h> /* clientData structure definition */ struct clientData { int acctNum; /* account number */ char lastName[ 15 ]; /* account last name */ char firstName[ 10 ]; /* account first name */ double balance; /* account balance */ }; /* end structure clientData */ /* prototypes */ int enterChoice( void ); void textFile( FILE *readPtr ); void updateRecord( FILE *fPtr ); void newRecord( FILE *fPtr ); void deleteRecord( FILE *fPtr ); int main() { FILE *cfPtr; /* credit.dat file pointer */ int choice; /* user's choice */ 42 /* fopen opens the file; exits if file cannot be opened */ if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { /* enable user to specify action */ while ( ( choice = enterChoice() ) != 5 ) { switch ( choice ) { /* create text file from record file */ case 1: textFile( cfPtr ); break; /* update record */ case 2: updateRecord( cfPtr ); break; /* create record */ case 3: newRecord( cfPtr ); break; 43 /* delete existing record */ case 4: deleteRecord( cfPtr ); break; /* display message if user does not select valid choice */ default: printf( "Incorrect choice\n" ); break; } /* end switch */ } /* end while */ fclose( cfPtr ); /* fclose closes the file */ } /* end else */ return 0; /* indicates successful termination */ } /* end main */ /* create formatted text file for printing */ void textFile( FILE *readPtr ) { FILE *writePtr; /* accounts.txt file pointer */ 44 /* create clientData with default information */ struct clientData client = { 0, "", "", 0.0 }; /* fopen opens the file; exits if file cannot be opened */ if ( ( writePtr = fopen( "accounts.txt", "w" ) ) == NULL ) { printf( "File could not be opened.\n" ); } /* end if */ else { rewind( readPtr ); /* sets pointer to beginning of file */ fprintf( writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" ); /* copy all records from random-access file into text file */ while ( !feof( readPtr ) ) { fread( &client, sizeof( struct clientData ), 1, readPtr ); /* write single record to text file */ if ( client.acctNum != 0 ) { fprintf( writePtr, "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); } /* end if */ } /* end while */ fclose( writePtr ); /* fclose closes the file */ } /* end else */ } /* end function textFile */ 45 /* update balance in record */ void updateRecord( FILE *fPtr ) { int account; /* account number */ double transaction; /* transaction amount */ /* create clientData with no information */ struct clientData client = { 0, "", "", 0.0 }; /* obtain number of account to update */ printf( "Enter account to update ( 1 - 100 ): " ); scanf( "%d", &account ); /* move file pointer to correct record in file */ fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ), SEEK_SET ); /* read record from file */ fread( &client, sizeof( struct clientData ), 1, fPtr ); /* display error if account does not exist */ if ( client.acctNum == 0 ) { printf( "Acount #%d has no information.\n", account ); } /* end if */ else { /* update record */ 46 printf( "%-6d%-16s%-11s%10.2f\n\n", client.acctNum, client.lastName, client.firstName, client.balance ); /* request transaction amount from user */ printf( "Enter charge ( + ) or payment ( - ): " ); scanf( "%lf", &transaction ); client.balance += transaction; /* update record balance */ printf( "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); /* move file pointer to correct record in file */ fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ), SEEK_SET ); /* write updated record over old record in file */ fwrite( &client, sizeof( struct clientData ), 1, fPtr ); } /* end else */ } /* end function updateRecord */ 47 /* delete an existing record */ void deleteRecord( FILE *fPtr ) { struct clientData client; /* stores record read from file */ struct clientData blankClient = { 0, "", "", 0 }; /* blank client */ int accountNum; /* account number */ /* obtain number of account to delete */ printf( "Enter account number to delete ( 1 - 100 ): " ); scanf( "%d", &accountNum ); /* move file pointer to correct record in file */ fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); /* read record from file */ fread( &client, sizeof( struct clientData ), 1, fPtr ); /* display error if record does not exist */ if ( client.acctNum == 0 ) { printf( "Account %d does not exist.\n", accountNum ); } /* end if */ else { /* delete record */ 48 /* move file pointer to correct record in file */ fseek( fPtr, ( accountNum-1 ) * sizeof( struct clientData ), SEEK_SET ); /* replace existing record with blank record */ fwrite( &blankClient, sizeof( struct clientData ), 1, fPtr ); } /* end else */ } /* end function deleteRecord */ /* create and insert record */ void newRecord( FILE *fPtr ) { /* create clientData with default information */ struct clientData client = { 0, "", "", 0.0 }; int accountNum; /* account number */ /* obtain number of account to create */ printf( "Enter new account number ( 1 - 100 ): " ); scanf( "%d", &accountNum ); /* move file pointer to correct record in file */ fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); 49 /* read record from file */ fread( &client, sizeof( struct clientData ), 1, fPtr ); /* display error if account already exists */ if ( client.acctNum != 0 ) { printf( "Account #%d already contains information.\n", client.acctNum ); } /* end if */ else { /* create record */ /* user enters last name, first name and balance */ printf( "Enter lastname, firstname, balance\n? " ); scanf( "%s%s%lf", &client.lastName, &client.firstName, &client.balance ); client.acctNum = accountNum; /* move file pointer to correct record in file */ fseek(fPtr, (client.acctNum-1) * sizeof( struct clientData ), SEEK_SET); /* insert record in file */ fwrite( &client, sizeof( struct clientData ), 1, fPtr ); } /* end else */ } /* end function newRecord */ 50 /* enable user to input menu choice */ int enterChoice( void ) { int menuChoice; /* variable to store user's choice */ /* display available options */ printf( "\nEnter your choice\n" "1 - store a formatted text file of acounts called\n" " \"accounts.txt\" for printing\n" "2 - update an account\n" "3 - add a new account\n" "4 - delete an account\n" "5 - end program\n? " ); scanf( "%d", &menuChoice ); /* receive choice from user */ return menuChoice; } /* end function enterChoice */ 51 After choosing option 1 accounts.txt contains: Acct 29 33 37 88 96 Last Name Brown Dunn Barker Smith Stone First Name Nancy Stacey Doug Dave Sam Balance -24.54 314.33 0.00 258.34 34.98 running option 2: Enter account to update ( 1 - 100 ): 37 37 Barker Doug 0.00 Enter charge ( + ) or payment ( - ): +87.99 37 Barker Doug 87.99 running option 2: Enter new account number ( 1 - 100 ): 22 Enter lastname, firstname, balance ? Johnston Sarah 247.45 52 Chapter 13 - The Preprocessor Outline 13.1 13.2 13.3 13.4 13.5 13.6 13.7 13.8 13.9 13.10 Introduction The #include Preprocessor Directive The #define Preprocessor Directive: Symbolic Constants The #define Preprocessor Directive: Macros Conditional Compilation The #error and #pragma Preprocessor Directives The # and ## Operators Line Numbers Predefined Symbolic Constants Assertions 53 13.1 Introduction • Preprocessing – – – – – Occurs before a program is compiled Inclusion of other files Definition of symbolic constants and macros Conditional compilation of program code Conditional execution of preprocessor directives • Format of preprocessor directives – Lines begin with # – Only whitespace characters before directives on a line 54 13.2 The #include Preprocessor Directive • #include – Copy of a specified file included in place of the directive – #include <filename> • Searches standard library for file • Use for standard library files – #include "filename" • Searches current directory, then standard library • Use for user-defined files – Used for: • Programs with multiple source files to be compiled together • Header file – has common declarations and definitions (classes, structures, function prototypes) – #include statement in each file 55 13.3 The #define Preprocessor Directive: Symbolic Constants • #define – Preprocessor directive used to create symbolic constants and macros – Symbolic constants • When program compiled, all occurrences of symbolic constant replaced with replacement text – Format #define identifier replacement-text – Example: #define PI 3.14159 – Everything to right of identifier replaces text #define PI = 3.14159 • Replaces “PI” with "= 3.14159" – Cannot redefine symbolic constants once they have been created 56 13.4 The #define Preprocessor Directive: Macros • Macro – Operation defined in #define – A macro without arguments is treated like a symbolic constant – A macro with arguments has its arguments substituted for replacement text, when the macro is expanded – Performs a text substitution – no data type checking – The macro #define CIRCLE_AREA( x ) ( PI * ( x ) * ( x ) ) would cause area = CIRCLE_AREA( 4 ); to become area = ( 3.14159 * ( 4 ) * ( 4 ) ); 57 13.4 The #define Preprocessor Directive: Macros • Use parenthesis – Without them the macro #define CIRCLE_AREA( x ) PI * x * x would cause area = CIRCLE_AREA( c + 2 ); to become area = 3.14159 * c + 2 * c + 2; • Multiple arguments #define RECTANGLE_AREA( x, y ) ( ( x ) * ( y ) ) would cause rectArea = RECTANGLE_AREA( a + 4, b + 7 ); to become rectArea = ( ( a + 4 ) * ( b + 7 ) ); 58 13.4 The #define Preprocessor Directive: Macros • If the replacement text for a macro or symbolic constant is longer than the remainder of the line, a backslash ( \ ) must be placed at the end of the line. • #undef – Undefines a symbolic constant or macro – If a symbolic constant or macro has been undefined it can later be redefined 59 13.5 Conditional Compilation • Conditional compilation – Control preprocessor directives and compilation – Cast expressions, sizeof, enumeration constants cannot be evaluated in preprocessor directives – Structure similar to if #if !defined( NULL ) #define NULL 0 #endif • Determines if symbolic constant NULL has been defined – If NULL is defined, defined( NULL ) evaluates to 1 – If NULL is not defined, this function defines NULL to be 0 – Every #if must end with #endif – #ifdef short for #if defined( name ) – #ifndef short for #if !defined( name ) 60 13.5 Conditional Compilation • Other statements – #elif – equivalent of else if in an if statement – #else – equivalent of else in an if statement • "Comment out" code – Cannot use /* ... */ – Use #if 0 code commented out #endif – To enable code, change 0 to 1 61 13.5 Conditional Compilation • Debugging #define DEBUG 1 #ifdef DEBUG cerr << "Variable x = " << x << endl; #endif – Defining DEBUG to 1 enables code – After code corrected, remove #define statement – Debugging statements are now ignored 62 13.6 The #error and #pragma Preprocessor Directives • #error tokens – Tokens are sequences of characters separated by spaces • "I like C++" has 3 tokens – Displays a message including the specified tokens as an error message – Stops preprocessing and prevents program compilation • #pragma tokens – Implementation defined action (consult compiler documentation) – Pragmas not recognized by compiler are ignored 63 13.7 The # and ## Operators • # – Causes a replacement text token to be converted to a string surrounded by quotes – The statement #define HELLO( x ) printf( “Hello, ” #x “\n” ); would cause HELLO( John ) to become printf( “Hello, ” “John” “\n” ); – Strings separated by whitespace are concatenated when using printf 64 13.7 The # and ## Operators • ## – Concatenates two tokens – The statement #define TOKENCONCAT( x, y ) x ## y would cause TOKENCONCAT( O, K ) to become OK 65 13.8 Line Numbers • #line – Renumbers subsequent code lines, starting with integer value – File name can be included – #line 100 "myFile.c" • Lines are numbered from 100 beginning with next source code file • Compiler messages will think that the error occurred in "myfile.C" • Makes errors more meaningful • Line numbers do not appear in source file 66 13.9 Predefined Symbolic Constants • Four predefined symbolic constants – Cannot be used in #define or #undef Sym b o lic c o n sta n t De sc rip tio n __LINE__ __FILE__ __DATE__ __TIME__ The line number of the current source code line (an integer constant). The presumed name of the source file (a string). The date the source file is compiled (a string of the form "Mmm dd yyyy" such as "Jan 19 2001"). The time the source file is compiled (a string literal of the form "hh:mm:ss"). 67 13.10 Assertions • assert macro – – – – Header <assert.h> Tests value of an expression If 0 (false) prints error message and calls abort Example: assert( x <= 10 ); – If NDEBUG is defined • All subsequent assert statements ignored #define NDEBUG 68
© Copyright 2024