Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Structure part 1 & File Processing. 2 Structures.

Similar presentations


Presentation on theme: "1 Structure part 1 & File Processing. 2 Structures."— Presentation transcript:

1 1 Structure part 1 & File Processing

2 2 Structures

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

4 4 Introduction Structures 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 E.g Object Characteristics Book price, number of pages, year published Car price, year, model, colour Student name, matric_no, semester

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

6 6 Structure Definition 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 define structure variables

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

8 8 How does it look like in my program? #include struct book { float price; int numpages; int year; }; int main( ) { struct book book1; …… } #include struct book { float price; int numpages; int year; } book1; int main( ) { …… } or

9 9 Initializing structures e.g. struct book book1={ 25.50, 690, 2005 }; OR book1.price = 25.50; book1.numpages=690; book1.year = 2005;

10 10 Operations on structure members OperationNormal variableStructure member Read from user scanf(“%f”, &price);scanf(“%f”, &book1.price); Assign valueprice = 25.50;book1.price = 25.50; Print as outputprintf(“%f\n”, price); printf(“%f\n”, book1.price); Copy to a variable newprice = price;newprice=book1.price; Pass value to a function if(fun1(price) > 5)if(fun1(book1.price) > 5)

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

12 12 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 hers\n”); else printf(“My book is cheaper than hers\n”);

13 13 Sample program #include 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("%.2f\t%d\t%d\n", my_book.price, my_book.numpages, my_book.year); printf("Her book :\n"); printf("%.2f\t%d\t%d\n", her_book.price, her_book.numpages, her_book.year); if(my_book.year > her_book.year) printf("My book is the latest publication\n"); else printf("Her book is the latest publication\n"); return 0; }

14 14 File Processing

15 15 Introduction 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

16 16 Introduction 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.

17 17 Data Hierarchy Bit Byte Field Record File 1 01011025 Judy Green JudyGreen SallyBlack TomBlue RandyRed

18 18 Files & Stream 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.

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

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

21 21 Creating a sequential file Output Enter the account, name and balance. Enter the EOF character to end input. ? 100Jones24.98 ? 200Doe345.67 ? 300White0.00 ? 400Stone -42.16 ?

22 22 Creating a sequential file The statement FILE *cfPtr, states that cfPtr is a pointer to a FILE structure. The statement if ((cfPtr = 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 cfPtr is assigned a pointer to the FILE structure for the file open with fopen(takes two argument i.e file name & file open mode).

23 23 Creating a sequential file 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.

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

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

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

27 27 Reading Data from Sequential File Output AccountNameBalance 100Jones24.98 200Doe345.67 300White0.00 400Stone-42.16

28 28 Random Access File 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.

29 29 Random Access File 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.

30 30 Creating a Randomly Accessed File 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.

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

32 32 Creating a Randomly Accessed File 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.

33 33 Creating a Randomly Accessed File #include struct clientData{ int acctNum; char lastName[15]; char firstName[15]; float balance;}; main(){ int i; struct clientData blankClient = {0, “ “, “ “, 0.0}; FILE *cfPtr; if((cfPtr = fopen(“credit.txt”, “w”)) = = NULL) printf(“file cant be open”); Else { for (I = 1; i<=100; i++) fwrite(&blankClient, sizeof(struct ClientData), 1, cfPtr); } fclose(cfPtr); return 0; } This program shows how to open a randomly access file, define a record format using struct, write a data to disk, and close the file. This program initialize all 100 records of a file “credit.txt” with empty struct using function fwrite

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

35 35 while (client.acctNum != 0){ printf(“Enter lastname, firstname, balance”); scanf(“%s%s%f, &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”); scanf(“%d”, &client.acctNum); } fclose(cfPtr); return 0; }

36 36 Writing Data Randomly to a Randomly Accessed File 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

37 37 Writing Data Randomly to a Randomly Accessed File The statement fseek(cfPtr, (client.acctNum – 1) * sizeof(struct clientData), SEEK_SET); positions the file position pointer for the file reference by cfPtr to the byte location calculated by (accountNum -1) * sizeof(struct clientData); 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.

38 38 Reading Data Randomly from a Randomly Accessed File #include struct clientData{ int acctNum; char lastName[15]; char firstName[15]; float balance; }; main(){ FILE *cfPtr; struct clientData client; if((cfPtr = fopen(“credit.txt”, “r”)) = = NULL) printf(“file cant be open”); else{ printf(“%-6s%-16s%-11s%10s\n”, “Acct”, “LastName”, “ First Name”, “Balance”);

39 39 while (!feof(cfPtr)){ fread(&client, sizeof(struct clientData), 1, cfPtr); if (client.acctNum != 0) printf(“(“%-6s %16s %11s %10.2f\n ”, client.acctNum, client.lastName, client.firstName, client.balance); } fclose (cfPtr); return 0; }

40 40 Reading Data Randomly from a Randomly Accessed File Output AcctLast NameFirst NameBalance 29 BrownNancy-24.54 30DunnStacey314.33 31BarkerDoug0.00 fread(&client, sizeof(struct clientData), 1, cfPtr); Reads the number of bytes determined by sizeof(struct clientData) from the file reference by cfPtr and stores the data in the structure client.


Download ppt "1 Structure part 1 & File Processing. 2 Structures."

Similar presentations


Ads by Google