Presentation is loading. Please wait.

Presentation is loading. Please wait.

File Processing (Cont.) and Structures

Similar presentations


Presentation on theme: "File Processing (Cont.) and Structures"— Presentation transcript:

1 File Processing (Cont.) and Structures
Lecture12 File Processing (Cont.) and Structures Dr. Serdar ÇELEBİ

2 Writing Data Randomly to a Random Access File
fseek Sets file position pointer to a specific position fseek( pointer, offset, symbolic_constant ); pointer – pointer to file offset – file position pointer (0 is first location) symbolic_constant – specifies where in file we are reading from SEEK_SET – seek starts at beginning of file SEEK_CUR – seek starts at current location in file SEEK_END – seek starts at end of file

3 1. Define struct 1.1 Initialize variables 2. Open file 2.1 Input data
1 /* Fig : fig11_12.c 2 Writing to a random access file */ 3 #include <stdio.h> 4 5 struct clientData { 6 int acctNum; 7 char lastName[ 15 ]; 8 char firstName[ 10 ]; 9 double balance; 10 }; 11 12 int main() 13 { 14 FILE *cfPtr; 15 struct clientData client = { 0, "", "", 0.0 }; 16 17 if ( ( cfPtr = fopen( "credit.dat", "r+" ) ) == NULL ) printf( "File could not be opened.\n" ); 19 else { printf( "Enter account number" " ( 1 to 100, 0 to end input )\n? " ); scanf( "%d", &client.acctNum ); 23 while ( client.acctNum != 0 ) { printf( "Enter lastname, firstname, balance\n? " ); fscanf( stdin, "%s%s%lf", client.lastName, client.firstName, &client.balance ); fseek( cfPtr, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); fwrite( &client, sizeof( struct clientData ), 1, cfPtr ); printf( "Enter account number\n? " ); 1. Define struct 1.1 Initialize variables 2. Open file 2.1 Input data 2.2 Write to file

4 3. Close file Program Output
scanf( "%d", &client.acctNum ); } 35 fclose( cfPtr ); 37 } 38 39 return 0; 40 } 3. Close file Program Output Enter account number (1 to 100, 0 to end input) ? 37 Enter lastname, firstname, balance ? Barker Doug 0.00 Enter account number ? 29 ? Brown Nancy ? 96 ? Stone Sam 34.98

5 Program Output Enter account number ? 88
Enter lastname, firstname, balance ? Smith Dave ? 33 ? Dunn Stacey ? 0 Program Output

6 Reading Data Sequentially from a Random Access File
fread Reads a specified number of bytes from a file into memory fread( &client, sizeof (struct clientData), 1, myPtr ); Can read several fixed-size array elements Provide pointer to array Indicate number of elements to read To read multiple elements, specify in third argument

7 1. Define struct 1.1 Initialize variables 2. Read (fread) 2.1 Print
1 /* Fig : fig11_15.c 2 Reading a random access file sequentially */ 3 #include <stdio.h> 4 5 struct clientData { 6 int acctNum; 7 char lastName[ 15 ]; 8 char firstName[ 10 ]; 9 double balance; 10 }; 11 12 int main() 13 { 14 FILE *cfPtr; 15 struct clientData client = { 0, "", "", 0.0 }; 16 17 if ( ( cfPtr = fopen( "credit.dat", "r" ) ) == NULL ) printf( "File could not be opened.\n" ); 19 else { printf( "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name", "Balance" ); 22 while ( !feof( cfPtr ) ) { fread( &client, sizeof( struct clientData ), 1, cfPtr ); 26 if ( client.acctNum != 0 ) printf( "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); } 32 1. Define struct 1.1 Initialize variables 2. Read (fread) 2.1 Print

8 3. Close file Program Output
fclose( cfPtr ); 34 } 35 36 return 0; 37 } 3. Close file Program Output Acct Last Name First Name Balance 29 Brown Nancy 33 Dunn Stacey 37 Barker Doug 88 Smith Dave 96 Stone Sam

9 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

10 1.3 Link pointer and open file
1 /* Fig : fig11_16.c 2 This program reads a random access file sequentially, 3 updates data already written to the file, creates new 4 data to be placed in the file, and deletes data 5 already in the file */ 6 #include <stdio.h> 7 8 struct clientData { 9 int acctNum; 10 char lastName[ 15 ]; 11 char firstName[ 10 ]; 12 double balance; 13 }; 14 15 int enterChoice( void ); 16 void textFile( FILE * ); 17 void updateRecord( FILE * ); 18 void newRecord( FILE * ); 19 void deleteRecord( FILE * ); 20 21 int main() 22 { 23 FILE *cfPtr; 24 int choice; 25 26 if ( ( cfPtr = fopen( "credit.dat", "r+" ) ) == NULL ) printf( "File could not be opened.\n" ); 28 else { 29 while ( ( choice = enterChoice() ) != 5 ) { 31 switch ( choice ) { 1. Define struct 1.1 Function prototypes 1.2 Initialize variables 1.3 Link pointer and open file 2. Input choice

11 2.1 Perform action 3. Close file 3.1 Function definitions
case 1: textFile( cfPtr ); break; case 2: updateRecord( cfPtr ); break; case 3: newRecord( cfPtr ); break; case 4: deleteRecord( cfPtr ); break; } } 47 fclose( cfPtr ); 49 } 50 51 return 0; 52 } 53 54 void textFile( FILE *readPtr ) 55 { 56 FILE *writePtr; 57 struct clientData client = { 0, "", "", 0.0 }; 58 59 if ( ( writePtr = fopen( "accounts.txt", "w" ) ) == NULL ) printf( "File could not be opened.\n" ); 61 else { rewind( readPtr ); fprintf( writePtr, "%-6s%-16s%-11s%10s\n", "Acct", "Last Name", "First Name","Balance" ); 2.1 Perform action 3. Close file 3.1 Function definitions

12 3.1 Function definitions 65 66 while ( !feof( readPtr ) ) {
fread( &client, sizeof( struct clientData ), 1, readPtr ); 69 if ( client.acctNum != 0 ) fprintf( writePtr, "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); } 75 fclose( writePtr ); 77 } 78 79 } 80 81 void updateRecord( FILE *fPtr ) 82 { 83 int account; 84 double transaction; 85 struct clientData client = { 0, "", "", 0.0 }; 86 87 printf( "Enter account to update ( ): " ); 88 scanf( "%d", &account ); 89 fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ), SEEK_SET ); 92 fread( &client, sizeof( struct clientData ), 1, fPtr ); 93 94 if ( client.acctNum == 0 ) printf( "Acount #%d has no information.\n", account ); 96 else { 3.1 Function definitions

13 3.1 Function definitions 97 printf( "%-6d%-16s%-11s%10.2f\n\n",
client.acctNum, client.lastName, client.firstName, client.balance ); printf( "Enter charge ( + ) or payment ( - ): " ); scanf( "%lf", &transaction ); client.balance += transaction; printf( "%-6d%-16s%-11s%10.2f\n", client.acctNum, client.lastName, client.firstName, client.balance ); fseek( fPtr, ( account - 1 ) * sizeof( struct clientData ), SEEK_SET ); fwrite( &client, sizeof( struct clientData ), 1, fPtr ); } 112 } 113 114 void deleteRecord( FILE *fPtr ) 115 { struct clientData client, blankClient = { 0, "", "", 0 }; int accountNum; 119 printf( "Enter account number to " "delete ( ): " ); scanf( "%d", &accountNum ); fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); fread( &client, sizeof( struct clientData ), 1, fPtr ); 3.1 Function definitions

14 3.1 Function definitions 127 128 if ( client.acctNum == 0 )
printf( "Account %d does not exist.\n", accountNum ); else { fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); fwrite( &blankClient, sizeof( struct clientData ), 1, fPtr ); } 137 } 138 139 void newRecord( FILE *fPtr ) 140 { struct clientData client = { 0, "", "", 0.0 }; int accountNum; printf( "Enter new account number ( ): " ); scanf( "%d", &accountNum ); fseek( fPtr, ( accountNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); fread( &client, sizeof( struct clientData ), 1, fPtr ); 149 if ( client.acctNum != 0 ) printf( "Account #%d already contains information.\n", client.acctNum ); else { printf( "Enter lastname, firstname, balance\n? " ); scanf( "%s%s%lf", &client.lastName, &client.firstName, &client.balance ); 3.1 Function definitions

15 3.1 Function definitions 157 client.acctNum = accountNum;
fseek( fPtr, ( client.acctNum - 1 ) * sizeof( struct clientData ), SEEK_SET ); fwrite( &client, sizeof( struct clientData ), 1, fPtr ); } 163 } 164 165 int enterChoice( void ) 166 { int menuChoice; 168 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 ); return menuChoice; 178 } 3.1 Function definitions

16 Program Output After choosing option 1 accounts.txt contains:
Acct Last Name First Name Balance 29 Brown Nancy 33 Dunn Stacey 37 Barker Doug 88 Smith Dave 96 Stone Sam Program Output Enter account to update ( ): 37 37 Barker Doug Enter charge (+) or payment (-): 37 Barker Doug Enter new account number ( ): 22 Enter lastname, firstname, balance ? Johnston Sarah

17 Structures

18 Introduction Structures
Collections of related variables (aggregates) under one name Can contain variables of different data types Commonly used to define records to be stored in files Combined with pointers, can create linked lists, stacks, queues, and trees

19 Structure Definitions
Example struct card { char *face; char *suit; }; struct introduces the definition for structure card card is the structure name and is used to declare variables of the structure type card contains two members of type char * These members are face and suit

20 Structure Definitions
struct information A struct cannot contain an instance of itself Can contain a member that is a pointer to the same structure type A structure definition does not reserve space in memory Instead creates a new data type used to declare structure variables Declarations Declared like other variables: card oneCard, deck[ 52 ], *cPtr; Can use a comma separated list: struct card { char *face; char *suit; } oneCard, deck[ 52 ], *cPtr;

21 Structure Definitions
Valid Operations Assigning a structure to a structure of the same type Taking the address (&) of a structure Accessing the members of a structure Using the sizeof operator to determine the size of a structure

22 Initializing Structures
Initializer lists Example: card oneCard = { "Three", "Hearts" }; Assignment statements card threeHearts = oneCard; Could also declare and initialize threeHearts as follows: card threeHearts; threeHearts.face = “Three”; threeHearts.suit = “Hearts”;

23 Accessing Members of Structures
Accessing structure members Dot operator (.) used with structure variables card myCard; printf( "%s", myCard.suit ); Arrow operator (->) used with pointers to structure variables card *myCardPtr = &myCard; printf( "%s", myCardPtr->suit ); myCardPtr->suit is equivalent to ( *myCardPtr ).suit

24 Using Structures With Functions
Passing structures to functions Pass entire structure Or, pass individual members Both pass call by value To pass structures call-by-reference Pass its address Pass reference to it To pass arrays call-by-value Create a structure with the array as a member Pass the structure

25 typedef typedef Creates synonyms (aliases) for previously defined data types Use typedef to create shorter type names Example: typedef struct Card *CardPtr; Defines a new type name CardPtr as a synonym for type struct Card * typedef does not create a new data type Only creates an alias

26 Example: High-Performance Card-shuffling and Dealing Simulation
Pseudocode: Create an array of card structures Put cards in the deck Shuffle the deck Deal the cards

27 1.3 Initialize deck[] and face[]
1 /* Fig. 10.3: fig10_03.c 2 The card shuffling and dealing program using structures */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 struct card { 8 const char *face; 9 const char *suit; 10 }; 11 12 typedef struct card Card; 13 14 void fillDeck( Card * const, const char *[], const char *[] ); 16 void shuffle( Card * const ); 17 void deal( const Card * const ); 18 19 int main() 20 { 21 Card deck[ 52 ]; 22 const char *face[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}; 27 const char *suit[] = { "Hearts", "Diamonds", "Clubs", "Spades"}; 29 30 srand( time( NULL ) ); 1. Load headers 1.1 Define struct 1.2 Function prototypes 1.3 Initialize deck[] and face[] 1.4 Initialize suit[]

28 2. fillDeck 2.1 shuffle 2.2 deal 3. Function definitions
31 32 fillDeck( deck, face, suit ); 33 shuffle( deck ); 34 deal( deck ); 35 return 0; 36 } 37 38 void fillDeck( Card * const wDeck, const char * wFace[], const char * wSuit[] ) 40 { 41 int i; 42 43 for ( i = 0; i <= 51; i++ ) { wDeck[ i ].face = wFace[ i % 13 ]; wDeck[ i ].suit = wSuit[ i / 13 ]; 46 } 47 } 48 49 void shuffle( Card * const wDeck ) 50 { 51 int i, j; 52 Card temp; 53 54 for ( i = 0; i <= 51; i++ ) { j = rand() % 52; temp = wDeck[ i ]; wDeck[ i ] = wDeck[ j ]; wDeck[ j ] = temp; 59 } 60 } 2. fillDeck 2.1 shuffle 2.2 deal 3. Function definitions Put all 52 cards in the deck. face and suit determined by remainder (modulus). Select random number between 0 and 51. Swap element i with that element.

29 Cycle through array and print out data. 3. Function definitions
61 62 void deal( const Card * const wDeck ) 63 { 64 int i; 65 66 for ( i = 0; i <= 51; i++ ) printf( "%5s of %-8s%c", wDeck[ i ].face, wDeck[ i ].suit, ( i + 1 ) % 2 ? '\t' : '\n' ); 70 } Cycle through array and print out data. 3. Function definitions

30 Program Output Eight of Diamonds Ace of Hearts
Eight of Clubs Five of Spades Seven of Hearts Deuce of Diamonds Ace of Clubs Ten of Diamonds Deuce of Spades Six of Diamonds Seven of Spades Deuce of Clubs Jack of Clubs Ten of Spades King of Hearts Jack of Diamonds Three of Hearts Three of Diamonds Three of Clubs Nine of Clubs Ten of Hearts Deuce of Hearts Ten of Clubs Seven of Diamonds Six of Clubs Queen of Spades Six of Hearts Three of Spades Nine of Diamonds Ace of Diamonds Jack of Spades Five of Clubs King of Diamonds Seven of Clubs Nine of Spades Four of Hearts Six of Spades Eight of Spades Queen of Diamonds Five of Diamonds Ace of Spades Nine of Hearts King of Clubs Five of Hearts King of Spades Four of Diamonds Queen of Hearts Eight of Hearts Four of Spades Jack of Hearts Four of Clubs Queen of Clubs Program Output


Download ppt "File Processing (Cont.) and Structures"

Similar presentations


Ads by Google