Structure part 1 File Processing 1 Structures 2

  • Slides: 40
Download presentation
Structure part 1 & File Processing 1

Structure part 1 & File Processing 1

Structures 2

Structures 2

Outline for Structure n n n Introduction Structure Definitions and declarations Initializing Structures Operations

Outline for Structure n n n Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions Parameters Arrays of structures and Structures of array 3

Introduction n Structures n n Collections of related data items called components(or members) that

Introduction n Structures n n Collections of related data items called components(or members) that are not necessarily of the same data type Each component in structure called field. Commonly used to define records (A group of information that may include more than one type of data) to be stored in files Usually the collections of related data item are characteristics in an object n n n E. g Object Book Car Student Characteristics price, number of pages, year published price, year, model, colour name, matric_no, semester 4

Structure Definition n Syntax struct Structure. Type. Name { structure member declaration list };

Structure Definition n Syntax struct Structure. Type. Name { structure member declaration list }; n E. g. struct book { float price; int numpages; int year; }; 5

Structure Definition n Struct information n A struct cannot contain an instance of itself

Structure Definition n Struct information n A struct cannot contain an instance of itself n Can contain a member that is a pointer to the same structure type n A structure definition does not reserve space in memory n Instead creates a new data type used to define structure variables 6

Structure Declaration n After defining a structure type, we may declare variables that are

Structure Declaration n After defining a structure type, we may declare variables that are of that type. A structure variable declaration requires these elements : n n keyword structure type name a list of variables names separated by commas A concluding semicolon E. g. struct book 1; 7

How does it look like in my program? #include <stdio. h> struct book {

How does it look like in my program? #include <stdio. h> struct book { float price; int numpages; int year; }; int main( ) { struct book 1; …… } or #include <stdio. h> struct book { float price; int numpages; int year; } book 1; int main( ) { …… } 8

Initializing structures e. g. struct book 1={ 25. 50, 690, 2005 }; OR book

Initializing structures e. g. struct book 1={ 25. 50, 690, 2005 }; OR book 1. price = 25. 50; book 1. numpages=690; book 1. year = 2005; 9

Operations on structure members Operation Normal variable Structure member Read from user scanf(“%f”, &price);

Operations on structure members Operation Normal variable Structure member Read from user scanf(“%f”, &price); scanf(“%f”, &book 1. price); Assign value price = 25. 50; book 1. price = 25. 50; Print as output printf(“%fn”, price); printf(“%fn”, book 1. price); Copy to a variable newprice=book 1. price; newprice = price; Pass value to a if(fun 1(price) > 5) function if(fun 1(book 1. price) > 5) 10

Multiple structure variables struct book my_book, his_book, her_book; q price q numpages q year

Multiple structure variables struct book my_book, his_book, her_book; q price q numpages q year my_book q price q numpages q year his_book q price q numpages q year her_book 11

Multiple structure variables e. g. struct book my_book, his_book, her_book; my_book. price = 25.

Multiple structure variables e. g. struct book my_book, his_book, her_book; my_book. price = 25. 50; her_book. price = 10. 50; if(my_book. price > her_book. price) printf(“My book is more expensive than hersn”); else printf(“My book is cheaper than hersn”); 12

Sample program #include <stdio. h> struct book { float price; int numpages; int year;

Sample program #include <stdio. h> struct book { float price; int numpages; int year; }; int main() { struct book my_book = {25. 50, 690, 2005}; struct book her_book; printf("Enter book price : "); scanf("%f", &her_book. price); printf("Enter number of pages : "); scanf("%d", &her_book. numpages); printf("Enter year published : "); scanf("%d", &her_book. year); printf("My book : n"); printf("%. 2 ft%dn", my_book. price, my_book. numpages, my_book. year); printf("Her book : n"); printf("%. 2 ft%dn", her_book. price, her_book. numpages, her_book. year); if(my_book. year > her_book. year) printf("My book is the latest publicationn"); else printf("Her book is the latest publicationn"); return 0; } 13

File Processing 14

File Processing 14

Introduction n n Almost all of the program developed before this is interactive In

Introduction n n Almost all of the program developed before this is interactive In interactive environment, input is via keyboard and output is via screen/monitor This type of processing is not suitable if it involves huge amount of input or output to be entered or be displayed on the screen at one time Therefore, file processing can solve the problem mentioned 15

Introduction n Storage of data in variables and array are temporary. File are used

Introduction n Storage of data in variables and array are temporary. File are used for permanent retention of large amount of data. Two type of files will be considered ; sequential access file and random access file. 16

Data Hierarchy Bit Byte Field Record File 1 01011025 Judy Green Sally Black Tom

Data Hierarchy Bit Byte Field Record File 1 01011025 Judy Green Sally Black Tom Blue Randy Red 17

Files & Stream n n n C views each file simply as a sequential

Files & Stream n n n C views each file simply as a sequential stream of bytes. When a file is opened, a stream is associated with the file. The files and their associated streams are automatically open when program executions begin, the standard input, the standard output and standard error. Stream provides communication channel between files and program. For example, standard input stream enable a program to read data from keyboard, the standard output stream enable a program to print data on screen. 18

Files & Stream n n Opening a file returns a pointer to a FILE

Files & Stream n n Opening a file returns a pointer to a FILE structure. Standard library provides many functions for reading data and writing data to files. 19

Creating a sequential file Consider the following example : #include<stdio. h> main () {

Creating a sequential file Consider the following example : #include<stdio. h> main () { int account; char name[30]; float balance; FILE *cf. Ptr; if ((cf. Ptr = fopen("clients. txt", "w")) == NULL) printf("File cant be opened"); else {printf("Enter account, name and balance. n"); printf("Enter EOF to end inputn"); printf("? "); scanf("%d%s%f", &account, name, &balance); n while (!feof(stdin)){ fprintf(cf. Ptr, "%d %s %. 2 fn", account, name, balance); printf("? "); scanf("%d%s%f", &account, name, &balance); } fclose(cf. Ptr); } return 0; } 20

Creating a sequential file n n n n Output Enter the account, name and

Creating a sequential file n n n n Output Enter the account, name and balance. Enter the EOF character to end input. ? 100 Jones 24. 98 ? 200 Doe 345. 67 ? 300 White 0. 00 ? 400 Stone -42. 16 ? 21

Creating a sequential file n n n The statement FILE *cf. Ptr , states

Creating a sequential file n n n The statement FILE *cf. Ptr , states that cf. Ptr is a pointer to a FILE structure. The statement if ((cf. Ptr = fopen("clients. txt", "w")) == NULL), names the file “clients. dat” to be used by the program and establish communication with the file. The file pointer cf. Ptr is assigned a pointer to the FILE structure for the file open with fopen(takes two argument i. e file name & file open mode). 22

Creating a sequential file n n File mode = r ( open file for

Creating a sequential file n n File mode = r ( open file for reading), w(create file for writing), a(append; open or create a for writing at the end of file), r+(open file for update – reading and writing), w+(create file for update), a+(append; open or create file for update) If file does not exist, fopen creates that file. 23

Creating a sequential file n The statement while(!feof(stdin)), n n n uses function feof

Creating a sequential file n The statement while(!feof(stdin)), n n n uses function feof to determine whether end-of-file indicator is set for file. EOF – for unix system and Mac is <ctrl> d and for IBM PC is <ctrl>z The statement fprintf(cf. Ptr, "%d %s %. 2 fn", account, name, balance), n writes data to the file clients. dat 24

Creating a sequential file n After user enters end-of-file, the program closes the clients.

Creating a sequential file n After user enters end-of-file, the program closes the clients. dat with fclose and terminates. 25

Reading Data from Sequential File n n Data stored in files so that can

Reading Data from Sequential File n n Data stored in files so that can be retrieved for processing when needed. Consider this program #include <stdio. h> main () { int account; char name[30]; float balance; FILE *cf. Ptr; if ((cf. Ptr = fopen("clients. txt", “r")) == NULL) printf("File cant be opened"); else { printf(“%-10 s%-13 s%sn”, “Account”, ”Name”, “Balance”); fscanf(cf. Ptr, “%d%s%f”, &account, name, &balance); printf(“%-10 d%13 s%7. 2 fn”, account, name, balance); fscanf(cf. Ptr, “%dtt%stt%f”, &account, name, &balance); } fclose(cf. Ptr); } return 0; } while(!feof(cf. Ptr)) { 26

Reading Data from Sequential File Output Account 100 200 300 400 n Name Jones

Reading Data from Sequential File Output Account 100 200 300 400 n Name Jones Doe White Stone Balance 24. 98 345. 67 0. 00 -42. 16 27

Random Access File n n In sequential access file, record in a file created

Random Access File n n In sequential access file, record in a file created with the formatted output function fprintf are not necessarily the same length. Individual records of a random access file are normally fixed in length This record can be accessed directly without searching through other record. Thus, the searching will be quicker It is suitable for the use of airline reservation system, banking system and other kind of transaction processing system. 28

Random Access File n n Because every record in randomly access file normally fixed

Random Access File n n Because every record in randomly access file normally fixed in length, data can be inserted in random access file without destroying other data. Data stored previously can also be updated or deleted without rewriting the entire file. 29

Creating a Randomly Accessed File n n n Function fwrite is used to transfer

Creating a Randomly Accessed File n n n Function fwrite is used to transfer a specified numbers of byte beginning at a specified location in memory to file. The data is written beginning at the location in the file indicated by the file position pointer. Function fread transfer a specified number of bytes from the file specified by the file position to an area in memory with a specified address. 30

Creating a Randomly Accessed File n Now, when writing an integer instead of using,

Creating a Randomly Accessed File n Now, when writing an integer instead of using, n n fprintf(f. Ptr, “%d”, number) which could print as few as 1 digit or as many as 11 digit, we can use fwrite(&number, sizeof(int), 1, f. Ptr) which always write 4 bytes from variable number to the file represented by f. Ptr. 31

Creating a Randomly Accessed File n n n fread is used to read 4

Creating a Randomly Accessed File n n n fread is used to read 4 of those bytes into integer variable number. The fread and fwrite functions are capable of reading and writing arrays of data to and from disk. The third argument of both is the number of element in array that should be read from disk or written to disk. The preceding fwrite function call writes a single integer to disk, so third argument is 1. File processing program rarely write a single field to a file. Normally, we write one struct at a time. 32

Creating a Randomly Accessed File #include <stdio. h> struct client. Data{ This program shows

Creating a Randomly Accessed File #include <stdio. h> struct client. Data{ This program shows how to open int acct. Num; a randomly access file, define a char last. Name[15]; record format using struct, write char first. Name[15]; a data to disk, and close the file. float balance; }; This program initialize all 100 main(){ records of a file “credit. txt” with int i; empty struct using function struct client. Data blank. Client = {0, “ “, 0. 0}; fwrite FILE *cf. Ptr; if((cf. Ptr = fopen(“credit. txt”, “w”)) = = NULL) printf(“file cant be open”); Else { for (I = 1; i<=100; i++) fwrite(&blank. Client, sizeof(struct Client. Data), 1, cf. Ptr); } fclose(cf. Ptr); return 0; } 33

Writing Data Randomly to a Randomly Accessed File n n #include <stdio. h> struct

Writing Data Randomly to a Randomly Accessed File n n #include <stdio. h> struct client. Data{ int acct. Num; char last. Name[15]; char first. Name[15]; float balance; }; n n main(){ FILE *cf. Ptr; struct client. Data client; if((cf. Ptr = fopen(“credit. txt”, “r+”)) = = NULL) n n printf(“file cant be open”); else{ n n print(“Enter account number(1 to 100, 0 to end input)”); scanf(“%d”, &client. acct. Num); 34

n while (client. acct. Num != 0){ n n n printf(“Enter lastname, firstname, balance”);

n while (client. acct. Num != 0){ n n n printf(“Enter lastname, firstname, balance”); scanf(“%s%s%f, &client. last. Name, &client. first. Name, &client. balance); fseek(cf. Ptr, (client. acct. Num – 1) * sizeof(struct client. Data), SEEK_SET); fwrite(&client, sizeof(struct client. Data), 1, cf. Ptr); printf(“Enter account number”); scanf(“%d”, &client. acct. Num); } } fclose(cf. Ptr); return 0; } 35

Writing Data Randomly to a Randomly Accessed File n Output Enter account number (1

Writing Data Randomly to a Randomly Accessed File n Output Enter account number (1 to 100, 0 to end) ? 29 Enter lastname, firstname, balance ? Brown Nancy -24. 54 Enter account number (1 to 100, 0 to end) ? 30 Enter lastname, firstname, balance ? Dunn Stacy 314. 33 Enter account number (1 to 100, 0 to end) ? 31 Enter lastname, firstname, balance ? Barker Doug 0. 00 Enter account number (1 to 100, 0 to end) ? 0 36

Writing Data Randomly to a Randomly Accessed File n n The statement fseek(cf. Ptr,

Writing Data Randomly to a Randomly Accessed File n n The statement fseek(cf. Ptr, (client. acct. Num – 1) * sizeof(struct client. Data), SEEK_SET); positions the file position pointer for the file reference by cf. Ptr to the byte location calculated by (account. Num -1) * sizeof(struct client. Data); Because of the account number is 1 to 100 but the byte positioning is start from 0, thus the account number need to minus 1. 37

Reading Data Randomly from a Randomly Accessed File #include <stdio. h> struct client. Data{

Reading Data Randomly from a Randomly Accessed File #include <stdio. h> struct client. Data{ int acct. Num; char last. Name[15]; char first. Name[15]; float balance; }; main(){ FILE *cf. Ptr; struct client. Data client; if((cf. Ptr = fopen(“credit. txt”, “r”)) = = NULL) printf(“file cant be open”); else{ printf(“%-6 s%-11 s%10 sn”, “Acct”, “Last. Name”, “ First Name”, “Balance”); 38

while (!feof(cf. Ptr)){ fread(&client, sizeof(struct client. Data), 1, cf. Ptr); if (client. acct. Num

while (!feof(cf. Ptr)){ fread(&client, sizeof(struct client. Data), 1, cf. Ptr); if (client. acct. Num != 0) printf(“(“%-6 s %11 s %10. 2 fn ”, client. acct. Num, client. last. Name, client. first. Name, client. balance); } } fclose (cf. Ptr); return 0; } 39

Reading Data Randomly from a Randomly Accessed File n Output Acct Last Name First

Reading Data Randomly from a Randomly Accessed File n Output Acct Last Name First Name Balance 29 Brown Nancy -24. 54 30 30 Dunn Stacey 314. 33 31 31 Barker Doug 0. 00 fread(&client, sizeof(struct client. Data), 1, cf. Ptr); Reads the number of bytes determined by sizeof(struct client. Data) from the file reference by cf. Ptr and stores the data in the structure client. 40