17
11 C File Processing OBJECTIVES In this chapter, you will learn: To create, read, write and update files. Sequential access file processing. Random-access file processing. I read part of it all the way through. —Samuel Goldwyn Hats off! The flag is passing by. —Henry Holcomb Bennett Consciousness … does not appear to itself chopped up in bits. … A “river” or a “stream” are the metaphors by which it is most naturally described. —William James I can only assume that a “Do Not File” document is filed in a “Do Not File” file. —Senator Frank Church

Chtp5e Pie Sm 11

Embed Size (px)

Citation preview

Page 1: Chtp5e Pie Sm 11

11C FileProcessing

O B J E C T I V E SIn this chapter, you will learn:

■ To create, read, write and update files.

■ Sequential access file processing.

■ Random-access file processing.

I read part of it all the waythrough.—Samuel Goldwyn

Hats off!The flag is passing by.—Henry Holcomb Bennett

Consciousness … does notappear to itself chopped upin bits. … A “river” or a“stream” are the metaphorsby which it is most naturallydescribed.—William James

I can only assume that a “DoNot File” document is filedin a “Do Not File” file.—Senator Frank Church

Page 2: Chtp5e Pie Sm 11

2 Chapter 11 C File Processing

Self-Review Exercises11.1 Fill in the blanks in each of the following:

a) Ultimately, all data items processed by a computer are reduced to combinations ofand .

ANS: 1s, 0s.b) The smallest data item a computer can process is called a(n) .ANS: bit.c) A(n) is a group of related records.ANS: file.d) Digits, letters and special symbols are referred to as .ANS: characters.e) A group of related files is called a .ANS: database.f) Function closes a file.ANS: fclose.g) The function reads data from a file in a manner similar to how scanf reads

from stdin.ANS: fscanf.h) Function reads a character from a specified file.ANS: fgetc.i) Function reads a line from a specified file.ANS: fgets.j) Function opens a file.ANS: fopen.k) Function is normally used when reading data from a file in random-access

applications.ANS: fread.l) Function repositions the file position pointer to a specific location in the file.ANS: fseek.

11.2 State which of the following are true and which are false. If false, explain why.a) Function fscanf cannot be used to read data from the standard input.ANS: False. Function fscanf can be used to read from the standard input by including the

pointer to the standard input stream, stdin, in the call to fscanf.b) You must explicitly use fopen to open the standard input, standard output and standard

error streams.ANS: False. These three streams are opened automatically by C when program execution begins.c) A program must explicitly call function fclose to close a file.ANS: False. The files will be closed when program execution terminates, but all files should

be explicitly closed with fclose.d) If the file position pointer points to a location in a sequential file other than the begin-

ning of the file, the file must be closed and reopened to read from the beginning of thefile.

ANS: False. Function rewind can be used to reposition the file position pointer to the be-ginning of the file.

e) Function fprintf can write to the standard output.ANS: True.f) Data in sequential-access files are always updated without overwriting other data.ANS: False. In most cases, sequential file records are not of uniform length. Therefore, it is

possible that updating a record will cause other data to be overwritten.

Page 3: Chtp5e Pie Sm 11

Self-Review Exercises 3

g) It is not necessary to search through all the records in a random-access file to find a specificrecord.

ANS: True.h) Records in random-access files are not of uniform length.ANS: False. Records in a random-access file are normally of uniform length.i) Function fseek may only seek relative to the beginning of a file.ANS: False. It is possible to seek from the beginning of the file, from the end of the file and

from the current location in the file.

11.3 Write a single statement to accomplish each of the following. Assume that each of thesestatements applies to the same program.

a) Write a statement that opens the file "oldmast.dat" for reading and assigns the re-turned file pointer to ofPtr.

ANS: ofPtr = fopen( "oldmast.dat", "r" );

b) Write a statement that opens the file "trans.dat" for reading and assigns the returnedfile pointer to tfPtr.

ANS: tfPtr = fopen( "trans.dat", "r" );

c) Write a statement that opens the file "newmast.dat" for writing (and creation) and as-signs the returned file pointer to nfPtr.

ANS: nfPtr = fopen( "newmast.dat", "w" );

d) Write a statement that reads a record from the file "oldmast.dat". The record consistsof integer accountNum, string name and floating-point currentBalance.

ANS: fscanf( ofPtr, "%d%s%f", &accountNum, name, &currentBalance );

e) Write a statement that reads a record from the file "trans.dat". The record consists ofthe integer accountNum and floating-point dollarAmount.

ANS: fscanf( tfPtr, "%d%f", &accountNum, &dollarAmount );

f) Write a statement that writes a record to the file "newmast.dat". The record consists ofthe integer accountNum, string name and floating-point currentBalance.

ANS: fprintf( nfPtr, "%d %s %.2f", accountNum, name, currentBalance );

11.4 Find the error in each of the following program segments and explain how to correct it.a) The file referred to by fPtr ("payables.dat") has not been opened.

printf( fPtr, "%d%s%d\n", account, company, amount );

ANS: Error: The file "payables.dat" has not been opened before the reference to its filepointer.Correction: Use fopen to open "payables.dat" for writing, appending or updating.

b) open( "receive.dat", "r+" );ANS: Error: Function open is not a Standard C function.

Correction: Use function fopen.c) The following statement should read a record from the file "payables.dat". File point-

er payPtr refers to this file, and file pointer recPtr refers to the file "receive.dat":scanf( recPtr, "%d%s%d\n", &account, company, &amount );

ANS: Error: Function fscanf uses the incorrect file pointer to refer to file "payables.dat".Correction: Use file pointer payPtr to refer to "payables.dat".

d) The file "tools.dat" should be opened to add data to the file without discarding thecurrent data.

if ( ( tfPtr = fopen( "tools.dat", "w" ) ) != NULL )

ANS: Error: The contents of the file are discarded because the file is opened for writing("w").Correction: To add data to the file, either open the file for updating ("r+") or openthe file for appending ("a").

Page 4: Chtp5e Pie Sm 11

4 Chapter 11 C File Processing

e) The file "courses.dat" should be opened for appending without modifying the currentcontents of the file.

if ( ( cfPtr = fopen( "courses.dat", "w+" ) ) != NULL )

ANS: Error: File "courses.dat" is opened for updating in "w+" mode which discards thecurrent contents of the file.Correction: Open the file "a" mode.

Exercises11.5 Fill in the blanks in each of the following:

a) Computers store large amounts of data on secondary storage devices as .ANS: files.b) A(n) is composed of several fields.ANS: record.c) A field that may contain digits, letters and blanks is called a(n) field.ANS: alphanumeric.d) To facilitate the retrieval of specific records from a file, one field in each record is chosen

as a(n) .ANS: key.e) The vast majority of information stored in computer systems is stored in

files.ANS: sequentialf) A group of related characters that conveys meaning is called a(n) .ANS: field.g) The file pointers for the three files that are opened automatically when program execu-

tion begins are named , and .ANS: stdin, stdout, stderr.h) Function writes a character to a specified file.ANS: fputc.i) Function writes a line to a specified file.ANS: fputs.j) Function is generally used to write data to a random-access file.ANS: fwrite.k) Function repositions the file position pointer to the beginning of the file.ANS: rewind.

11.6 Exercise 11.3 asked the reader to write a series of single statements. Actually, these state-ments form the core of an important type of file-processing program, namely, a file-matching pro-gram. In commercial data processing, it is common to have several files in each system. In anaccounts receivable system, for example, there is generally a master file containing detailed informa-tion about each customer such as the customer’s name, address, telephone number, outstanding bal-ance, credit limit, discount terms, contract arrangements and possibly a condensed history of recentpurchases and cash payments.

As transactions occur (i.e., sales are made and cash payments arrive in the mail), they areentered into a file. At the end of each business period (i.e., a month for some companies, a week forothers and a day in some cases) the file of transactions (called "trans.dat" in Exercise 11.3) isapplied to the master file (called "oldmast.dat" in Exercise 11.3), thus updating each account'srecord of purchases and payments. After each of these updatings run, the master file is rewritten asa new file ("newmast.dat"), which is then used at the end of the next business period to begin theupdating process again.

Page 5: Chtp5e Pie Sm 11

Exercises 5

File-matching programs must deal with certain problems that do not exist in single-file pro-grams. For example, a match does not always occur. A customer on the master file might not havemade any purchases or cash payments in the current business period, and therefore no record forthis customer will appear on the transaction file. Similarly, a customer who did make some pur-chases or cash payments might have just moved to this community, and the company may not havehad a chance to create a master record for this customer.

Use the statements written in Exercise 11.3 as the basis for a complete file-matching accountsreceivable program. Use the account number on each file as the record key for matching purposes.Assume that each file is a sequential file with records stored in increasing account number order.

When a match occurs (i.e., records with the same account number appear on both the masterfile and the transaction file), add the dollar amount on the transaction file to the current balance onthe master file and write the "newmast.dat" record. (Assume that purchases are indicated by posi-tive amounts on the transaction file, and that payments are indicated by negative amounts.) Whenthere is a master record for a particular account but no corresponding transaction record, merelywrite the master record to "newmast.dat". When there is a transaction record but no cor-responding master record, print the message "Unmatched transaction record for account number

…" (fill in the account number from the transaction record).ANS:

1 /* Exercise 11.6 Solution */2 /* NOTE: This program was run using the */3 /* data in Exercise 11.7 */4 #include <stdio.h>5 #include <stdlib.h>67 int main( void )8 {9 int masterAccount; /* account from old master file */

10 int transactionAccount; /* account from transactions file */11 double masterBalance; /* balance from old master file */12 double transactionBalance; /* balance from transactions file */13 char masterName[ 30 ]; /* name from master file */14 FILE *ofPtr; /* old master file pointer */15 FILE *tfPtr; /* transactions file pointer */16 FILE *nfPtr; /* new master file pointer */1718 /* terminate application if old master file cannot be opened */19 if ( ( ofPtr = fopen( "oldmast.dat", "r" ) ) == NULL ) {20 printf( "Unable to open oldmast.dat\n" );21 exit( 1 );22 } /* end if */2324 /* terminate application if transactions file cannot be opened */25 if ( ( tfPtr = fopen( "trans.dat", "r" ) ) == NULL ) {26 printf( "Unable to open trans.dat\n" );27 exit( 1 );28 } /* end if */2930 /* terminate application if new master file cannot be opened */31 if ( ( nfPtr = fopen( "newmast.dat", "w" ) ) == NULL ) {32 printf( "Unable to open newmast.dat\n" );33 exit( 1 );34 } /* end if */

Page 6: Chtp5e Pie Sm 11

6 Chapter 11 C File Processing

3536 /* display account currently being processed */37 printf( "Processing....\n" );38 fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance );3940 /* while not the end of transactions file */41 while ( !feof( tfPtr ) ) {4243 /* read next record from old master file */44 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName,45 &masterBalance );4647 /* display accounts from master file until number of48 new account is reached */49 while ( masterAccount < transactionAccount && !feof( ofPtr ) ) {50 fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName,51 masterBalance );52 printf( "%d %s %.2f\n", masterAccount, masterName,53 masterBalance );5455 /* read next record from old master file */56 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount,57 masterName, &masterBalance );58 } /* end while */5960 /* if matching account found, update balance and output61 account info */62 if ( masterAccount == transactionAccount ) {63 masterBalance += transactionBalance;64 fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName,65 masterBalance );66 printf( "%d %s %.2f\n", masterAccount, masterName,67 masterBalance );68 } /* end if */6970 /* tell user if account from transactions file does71 not match account from master file */72 else if ( masterAccount > transactionAccount ) {73 printf( "Unmatched transaction record for account %d\n",74 transactionAccount );75 fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName,76 masterBalance );77 printf( "%d %s %.2f\n", masterAccount, masterName,78 masterBalance );79 } /* end else if */80 else {81 printf( "Unmatched transaction record for account %d\n",82 transactionAccount );83 } /* end else */8485 /* get next account and balance from transactions file */86 fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance );87 } /* end while */88

Page 7: Chtp5e Pie Sm 11

Exercises 7

11.7 After writing the program of Exercise 11.6, write a simple program to create some test datafor checking out the program of Exercise 11.6. Use the following sample account data:

89 /* loop through file and display account number, name and balance */90 while ( !feof( ofPtr ) ) {91 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName,92 &masterBalance );93 fprintf( nfPtr, "%d %s %.2f", masterAccount, masterName,94 masterBalance );95 printf( "%d %s %.2f", masterAccount, masterName, masterBalance );96 } /* end while */9798 fclose( ofPtr ); /* close all file pointers */99 fclose( tfPtr );100 fclose( nfPtr );101102 return 0; /* indicate successful termination */103104 } /* end main */

Processing....100 Alan Jones 375.31300 Mary Smith 89.30Unmatched transaction record for account 400500 Sam Sharp 0.00700 Suzy Green -14.22Unmatched transaction record for account 900

Master File:Account number Name Balance

100 Alan Jones 348.17

300 Mary Smith 27.19

500 Sam Sharp 0.00

700 Suzy Green -14.22

Transaction File:Account number Dollar amount

100 27.14

300 62.11

400 100.56

900 82.17

Page 8: Chtp5e Pie Sm 11

8 Chapter 11 C File Processing

ANS:

1 /* Exercise 11.7 Solution */2 #include <stdio.h>34 int main( void )5 {6 int account; /* account number */7 char name[ 30 ]; /* account name */8 double balance; /* account balance */9 double amount; /* transaction amount */

10 FILE *ofPtr; /* old master file pointer */11 FILE *tfPtr; /* transaction file pointer */1213 /* open both files for writing */14 ofPtr = fopen( "oldmast.dat", "w" );15 tfPtr = fopen( "trans.dat", "w" );1617 /* prompt user for sample data */18 printf( "Sample data for file oldmast.dat:\n" );19 printf( "Enter account, name, and balance (EOF to end): " );2021 /* loop while EOF character not entered by user */22 while ( scanf( "%d%[^0-9-]%lf", &account, name,23 &balance ) != EOF ) {2425 /* write data to old master file */26 fprintf( ofPtr, "%d %s %.2f\n", account, name, balance );27 printf( "Enter account, name, and balance (EOF to end): " );28 } /* end while */2930 fclose( ofPtr ); /* close file pointer */3132 /* prompt user for sample data */33 printf( "\nSample data for file trans.dat:\n" );34 printf( "Enter account and transaction amount (EOF to end): " );3536 /* loop while EOF character not entered by user */37 while ( scanf( "%d%lf", &account, &amount ) != EOF ) {38 /* write data to transactions file */39 fprintf( tfPtr, "%d %.2f\n", account, amount );40 printf( "Enter account and transaction amount (EOF to end): " );41 } /* end while */4243 fclose( tfPtr ); /* close file pointer */4445 return 0; /* indicate successful termination */4647 } /* end main */

Page 9: Chtp5e Pie Sm 11

Exercises 9

11.8 Run the program of Exercise 11.6 using the files of test data created in Exercise 11.7. Usethe listing program of Section 11.7 to print the new master file. Check the results carefully.

11.9 It is possible (actually common) to have several transaction records with the same recordkey. This occurs because a particular customer might make several purchases and cash paymentsduring a business period. Rewrite your accounts receivable file-matching program of Exercise 11.6to provide for the possibility of handling several transaction records with the same record key. Mod-ify the test data of Exercise 11.7 to include the following additional transaction records:

ANS:

Sample data for file oldmast.dat:Enter account, name, and balance (EOF to end): 100 Alan Jones 348.17Enter account, name, and balance (EOF to end): 300 Mary Smith 27.19Enter account, name, and balance (EOF to end): 500 Sam Sharp 0.00Enter account, name, and balance (EOF to end): 700 Suzy Green -14.22Enter account, name, and balance (EOF to end): ^Z

Sample data for file trans.dat:Enter account and transaction amount (EOF to end): 100 27.14Enter account and transaction amount (EOF to end): 300 62.11Enter account and transaction amount (EOF to end): 400 100.56Enter account and transaction amount (EOF to end): 900 82.17Enter account and transaction amount (EOF to end): ^Z

Account number Dollar amount

300 83.89

700 80.78

700 1.53

1 /* Exercise 11.9 Solution */2 #include <stdio.h>3 #include <stdlib.h>45 int main( void )6 {7 int masterAccount; /* account from old master file */8 int transactionAccount; /* account from transactions file */9 double masterBalance; /* balance from old master file */

10 double transactionBalance; /* balance from transactions file */11 char masterName[ 30 ]; /* name from master file */12 FILE *ofPtr; /* old master file pointer */13 FILE *tfPtr; /* transactions file pointer */14 FILE *nfPtr; /* new master file pointer */1516 /* terminate application if old master file cannot be opened */17 if ( ( ofPtr = fopen( "oldmast.dat", "r" ) ) == NULL ) {18 printf( "Unable to open oldmast.dat\n" );19 exit( 1 );20 } /* end if */

Page 10: Chtp5e Pie Sm 11

10 Chapter 11 C File Processing

2122 /* terminate application if transactions file cannot be opened */23 if ( ( tfPtr = fopen( "trans.dat", "r" ) ) == NULL ) {24 printf( "Unable to open trans.dat\n" );25 exit( 1 );26 } /* end if */2728 /* terminate application if new master file cannot be opened */29 if ( ( nfPtr = fopen( "newmast.dat", "w" ) ) == NULL ) {30 printf( "Unable to open newmast.dat\n" );31 exit( 1 );32 } /* end if */3334 /* display account currently being processed */35 printf( "Processing....\n" );36 fscanf( tfPtr, "%d%lf", &transactionAccount, &transactionBalance );3738 /* while not the end of transactions file */39 while ( !feof( tfPtr ) ) {4041 /* read next record from old master file */42 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName,43 &masterBalance );4445 /* display accounts from master file until number of46 new account is reached */47 while ( masterAccount < transactionAccount && !feof( ofPtr ) ) {48 fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName,49 masterBalance );50 printf( "%d %s %.2f\n", masterAccount, masterName,51 masterBalance );5253 /* read next record from old master file */54 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount,55 masterName, &masterBalance );56 } /* end while */5758 /* if matching account found, update balance and output59 account info */60 if ( masterAccount == transactionAccount ) {6162 /* while more transactions exist for current account */63 while ( masterAccount == transactionAccount &&64 !feof( tfPtr ) ) {6566 /* update masterBalance and read next record */67 masterBalance += transactionBalance;68 fscanf( tfPtr, "%d%lf", &transactionAccount,69 &transactionBalance );70 } /* end while */7172 fprintf( nfPtr, "%d %s %.2f\n",73 masterAccount, masterName, masterBalance );74 printf("%d %s %.2f\n", masterAccount, masterName, masterBalance);75 } /* end if */

Page 11: Chtp5e Pie Sm 11

Exercises 11

11.10 Write statements that accomplish each of the following. Assume that the structure

struct person {char lastName[ 15 ];char firstName[ 15 ];char age[ 4 ];

};

has been defined and that the file is already open for writing.

7677 /* tell user if account from transactions file does78 not match account from master file */79 else if ( masterAccount > transactionAccount ) {80 printf( "Unmatched transaction record for account %d\n",81 transactionAccount );82 fprintf( nfPtr, "%d %s %.2f\n", masterAccount, masterName,83 masterBalance );84 printf("%d %s %.2f\n", masterAccount, masterName, masterBalance);85 fscanf(tfPtr, "%d%lf", &transactionAccount, &transactionBalance);86 } /* end else if */87 else {88 printf( "Unmatched transaction record for account %d\n",89 transactionAccount );90 fscanf(tfPtr, "%d%lf", &transactionAccount, &transactionBalance);91 } /* end else */9293 } /* end while */9495 /* loop through file and display account number, name and balance */96 while ( !feof( ofPtr ) ) {97 fscanf( ofPtr, "%d%[^0-9-]%lf", &masterAccount, masterName,98 &masterBalance );99 fprintf( nfPtr, "%d %s %.2f", masterAccount, masterName,100 masterBalance );101 printf( "%d %s %.2f", masterAccount, masterName, masterBalance );102 } /* end while */103104 fclose( ofPtr ); /* close all file pointers */105 fclose( tfPtr );106 fclose( nfPtr );107108 return 0; /* indicate successful termination */109110 } /* end main */

Processing....100 Alan Jones 375.31300 Mary Smith 173.19Unmatched transaction record for account 400500 Sam Sharp 0.00700 Suzy Green 68.09Unmatched transaction record for account 900

Page 12: Chtp5e Pie Sm 11

12 Chapter 11 C File Processing

a) Initialize the file "nameage.dat" so that there are 100 records with lastName = "unas-

signed", firstname = "" and age = "0".b) Input 10 last names, first names and ages, and write them to the file.c) Update a record; if there is no information in the record, tell the user "No info".d) Delete a record that has information by reinitializing that particular record.

11.11 You are the owner of a hardware store and need to keep an inventory that can tell you whattools you have, how many you have and the cost of each one. Write a program that initializes thefile "hardware.dat" to 100 empty records, lets you input the data concerning each tool, enables youto list all your tools, lets you delete a record for a tool that you no longer have and lets you updateany information in the file. The tool identification number should be the record number. Use thefollowing information to start your file:

11.12 Telephone Number Word Generator. Standard telephone keypads contain the digits 0 through9. The numbers 2 through 9 each have three letters associated with them, as is indicated by the fol-lowing table:

Many people find it difficult to memorize phone numbers, so they use the correspondencebetween digits and letters to develop seven-letter words that correspond to their phone numbers.For example, a person whose telephone number is 686-2377 might use the correspondence indi-cated in the above table to develop the seven-letter word “NUMBERS.”

Record # Tool name Quantity Cost

3 Electric sander 7 57.98

17 Hammer 76 11.99

24 Jig saw 21 11.00

39 Lawn mower 3 79.50

56 Power saw 18 99.99

68 Screwdriver 106 6.99

77 Sledge hammer 11 21.50

83 Wrench 34 7.50

Digit Letter Digit Letter

2 A B C 6 M N O

3 D E F 7 P R S

4 G H I 8 T U V

5 J K L 9 W X Y

Page 13: Chtp5e Pie Sm 11

Exercises 13

Businesses frequently attempt to get telephone numbers that are easy for their clients toremember. If a business can advertise a simple word for its customers to dial, then no doubt thebusiness will receive a few more calls.

Each seven-letter word corresponds to exactly one seven-digit telephone number. The restau-rant wishing to increase its take-home business could surely do so with the number 825-3688 (i.e.,“TAKEOUT”).

Each seven-digit phone number corresponds to many separate seven-letter words. Unfortu-nately, most of these represent unrecognizable juxtapositions of letters. It is possible, however, thatthe owner of a barber shop would be pleased to know that the shop’s telephone number, 424-7288,corresponds to “HAIRCUT.” The owner of a liquor store would, no doubt, be delighted to findthat the store’s telephone number, 233-7226, corresponds to “BEERCAN.” A veterinarian with thephone number 738-2273 would be pleased to know that the number corresponds to the letters“PETCARE.”

Write a C program that, given a seven-digit number, writes to a file every possible seven-letterword corresponding to that number. There are 2187 (3 to the seventh power) such words. Avoidphone numbers with the digits 0 and 1.

ANS:

1 /* Exercise 11.12 Solution */2 #include <stdio.h>34 void wordGenerator( int number[] ); /* prototype */56 int main( void )7 {8 int loop; /* loop counter */9 int phoneNumber[ 7 ] = { 0 }; /* holds phone number */

1011 /* prompt user to enter phone number */12 printf( "Enter a phone number one digit at a time" );13 printf( " using the digits 2 thru 9:\n" );1415 /* loop 7 times to get number */16 for ( loop = 0; loop <= 6; loop++ ) {17 printf( "? " );18 scanf( "%d", &phoneNumber[ loop ] );1920 /* test if number is between 0 and 9 */21 while ( phoneNumber[ loop ] < 2 || phoneNumber[ loop ] > 9 ) {22 printf( "\nInvalid number entered. Please enter again: " );23 scanf( "%d", &phoneNumber[ loop ] );24 } /* end while */2526 } /* end for */2728 wordGenerator( phoneNumber ); /* form words from phone number */2930 return 0; /* indicate successful termination */3132 } /* end main */3334 /* function to form words based on phone number */35 void wordGenerator( int number[] )

Page 14: Chtp5e Pie Sm 11

14 Chapter 11 C File Processing

36 {37 int loop; /* loop counter */38 int loop1; /* loop counter for first digit of phone number */39 int loop2; /* loop counter for second digit of phone number */40 int loop3; /* loop counter for third digit of phone number */41 int loop4; /* loop counter for fourth digit of phone number */42 int loop5; /* loop counter for fifth digit of phone number */43 int loop6; /* loop counter for sixth digit of phone number */44 int loop7; /* loop counter for seventh digit of phone number */45 FILE *foutPtr; /* output file pointer */4647 /* letters corresponding to each number */48 char *phoneLetters[ 10 ] = { "", "", "ABC", "DEF", "GHI", "JKL",49 "MNO", "PRS", "TUV", "WXY"};5051 /* open output file */52 if ( ( foutPtr = fopen( "phone.out", "w" ) ) == NULL ) {53 printf( "Output file was not opened.\n" );54 } /* end if */55 else { /* print all possible combinations */5657 for ( loop1 = 0; loop1 <= 2; loop1++ ) {5859 for ( loop2 = 0; loop2 <= 2; loop2++ ) {6061 for ( loop3 = 0; loop3 <= 2; loop3++ ) {6263 for ( loop4 = 0; loop4 <= 2; loop4++ ) {6465 for ( loop5 = 0; loop5 <= 2; loop5++ ) {6667 for ( loop6 = 0; loop6 <= 2; loop6++ ) {6869 for ( loop7 = 0; loop7 <= 2; loop7++ ) {70 fprintf( foutPtr, "%c%c%c%c%c%c%c\n",71 phoneLetters[ number[ 0 ] ][ loop1 ],72 phoneLetters[ number[ 1 ] ][ loop2 ],73 phoneLetters[ number[ 2 ] ][ loop3 ],74 phoneLetters[ number[ 3 ] ][ loop4 ],75 phoneLetters[ number[ 4 ] ][ loop5 ],76 phoneLetters[ number[ 5 ] ][ loop6 ],77 phoneLetters[ number[ 6 ] ][ loop7 ] );78 } /* end for */7980 } /* end for */8182 } /* end for */8384 } /* end for */8586 } /* end for */8788 } /* end for */8990 } /* end for */

Page 15: Chtp5e Pie Sm 11

Exercises 15

The contents of phone.out are:

11.13 Write a program that uses the sizeof operator to determine the sizes in bytes of the variousdata types on your computer system. Write the results to the file "datasize.dat" so you may printthe results later. The format for the results in the file should be as follows:

9192 /* output phone number */93 fprintf( foutPtr, "\nPhone number is " );9495 /* loop through digits */96 for ( loop = 0; loop <= 6; loop++ ) {9798 /* insert hyphen */99 if ( loop == 3 ) {100 fprintf( foutPtr, "-" );101 } /* end if */102103 fprintf( foutPtr, "%d", number[ loop ] );104 } /* end for */105106 } /* end else */107108 fclose( foutPtr ); /* close file pointer */

Enter a phone number one digit at a time using the digits 2 thru 9:? 8? 4? 3? 2? 6? 7? 7

TGDAMPPTGDAMPRTGDAMPSTGDAMRPTGDAMRRTGDAMRSTGDAMSPTGDAMSR...VIFCORPVIFCORRVIFCORSVIFCOSPVIFCOSRVIFCOSS

Phone number is 843-2677

Page 16: Chtp5e Pie Sm 11

16 Chapter 11 C File Processing

[Note: The type sizes on your computer might be different from those listed above.]ANS:

Data type Sizechar 1unsigned char 1short int 2unsigned short int 2int 4unsigned int 4long int 4unsigned long int 4float 4double 8long double 16

1 /* Exercise 11.13 Solution */2 #include <stdio.h>34 int main( void )56 {7 FILE *outPtr; /* output file pointer */89 /* open datasize.dat for writing */

10 outPtr = fopen( "datasize.dat", "w" );1112 /* write size of various data types */13 fprintf( outPtr, "%s%16s\n", "Data type", "Size" );14 fprintf( outPtr, "%s%21d\n", "char", sizeof( char ) );15 fprintf( outPtr, "%s%12d\n", "unsigned char",16 sizeof( unsigned char ) );17 fprintf( outPtr, "%s%16d\n", "short int", sizeof( short int ) );18 fprintf( outPtr, "%s%7d\n", "unsigned short int",19 sizeof( unsigned short int ) );20 fprintf( outPtr, "%s%22d\n", "int", sizeof( int ) );21 fprintf( outPtr, "%s%13d\n", "unsigned int",22 sizeof( unsigned int ) );23 fprintf( outPtr, "%s%17d\n", "long int", sizeof( long int ) );24 fprintf( outPtr, "%s%8d\n", "unsigned long int",25 sizeof( unsigned long int ) );26 fprintf( outPtr, "%s%20d\n", "float", sizeof( float ) );27 fprintf( outPtr, "%s%19d\n", "double", sizeof( double ) );28 fprintf( outPtr, "%s%14d\n", "long double", sizeof( long double ) );2930 fclose( outPtr ); /* close file pointer */3132 return 0; /* indicate successful termination */3334 } /* end main */

Page 17: Chtp5e Pie Sm 11

Exercises 17

Contents of datasize.dat:

Data type Sizechar 1unsigned char 1short int 2unsigned short int 2int 4unsigned int 4long int 4unsigned long int 4float 4double 8long double 8