1 Structure part 1 & File Processing. 2 Structures.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
Chapter 11: Data Files & File Processing In this chapter, you will learn about Files and streams Creating a sequential access file Reading data from a.
File processing with functions H&K Chapter 3 Instructor – Gokcen Cilingir Cpt S 121 (June 27, 2011) Washington State University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Data files –Can be created, updated,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Chapter 11 C File Processing Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Lec11: File Processing 廖雪花 TEL: 年 5 月.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating.
Lecture 11 – Files Operation. Introduction Almost all of the program developed before this is interactive In interactive environment, input is via keyboard.
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Programming Practice Introduction Tree Operations. Binary Search Tree. File Processing Create, read, write and update files. Sequential.
1 File Processing Dr. Serdar ÇELEBİ. 2 Outline Introduction The Data Hierarchy Files and Streams Creating a Sequential Access File Reading Data from a.
1 Structures UniMAP SEM I - 11/12EKT 120 Computer Programming.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
Text and Binary File Processing 程式設計 潘仁義 CCU COMM.
1. Introduction File Declaration and Initialization Creating and Opening File Closing File EOF Reading from and Writing into a File Extra : Random Access.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
Chapter 8 File-Oriented Input and Output. 8.1 INTRODUCTION a file can also be designed to store data. We can easily update files, A data file as input.
Chapter 11: Data Files and File Processing Files and streams Creating a sequential access file Reading data from a sequential access file Using fgetc()
Chapter 11 File Processing. Objectives In this chapter, you will learn: –To be able to create, read, write and update files. –To become familiar with.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Introduction Introduce some standard library functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Data files –Can be created, updated, and processed by C programs –Are used for permanent.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 11 – File Processing Outline 11.1Introduction.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
C Program Design C File Processing 主講人:虞台文. Content Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
C File Processing. Objectives To be able to create, write and update files. To become familiar with sequential access file processing. To become familiar.
Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures as Functions.
ME-2221 COMPUTER PROGRAMMING Lecture 18 FILE OPERATIONS Department of Mechanical Engineering A.H.M Fazle Elahi Khulna University of engineering & Technology.
Chapter 12 Files (reference: Deitel ’ s chap 11) chap8.
File Access Storage of data in variables and arrays is temporary—such data is lost when a program terminates. Files are used for permanent retention of.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
File Processing Part 2. Random Access File In sequential access file, record in a file created with the formatted output function fprintf are not necessarily.
1. 2 Introduction Structure Definitions and Declarations Initializing Structures Operations on Structures Members Structures as Functions Parameters Array.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
Files. FILE * u In C, we use a FILE * data type to access files. u FILE * is defined in /usr/include/stdio.h u An example: #include int main() { FILE.
Lecture 20: C File Processing. Why Using Files? Storage of data in variables and arrays is temporary Data lost when a program terminates. Files are used.
1 Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating a Sequential Access File 11.5Reading.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني I/O and File management(cont.) Binary and random files.
Lecture 10: Structures. Outline Introduction Structure Definitions and declarations Initializing Structures Operations on Structures members Structures.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
Chapter 11 – File Processing
11 C File Processing.
File Processing Part 2.
Chapter 4 File Processing
TMF1414 Introduction to Programming
EKT120: Computer Programming
Introduction to Computer Programming Lecture 18 Binary Files
File Processing (Cont.) and Structures
Chapter 11 – File Processing
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Text and Binary File Processing
Fundamental of Programming (C)
Pertemuan 14 File Processing II
EPSII 59:006 Spring 2004.
EPSII 59:006 Spring 2004.
Chapter 11 Files chap8.
Presentation transcript:

1 Structure part 1 & File Processing

2 Structures

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 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 Structure Definition Syntax struct StructureTypeName { structure member declaration list }; E.g. struct book { float price; int numpages; int year; };

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 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 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 Initializing structures e.g. struct book book1={ 25.50, 690, 2005 }; OR book1.price = 25.50; book1.numpages=690; book1.year = 2005;

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 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 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 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 File Processing

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 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 Data Hierarchy Bit Byte Field Record File Judy Green JudyGreen SallyBlack TomBlue RandyRed

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 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 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 Creating a sequential file Output Enter the account, name and balance. Enter the EOF character to end input. ? 100Jones24.98 ? 200Doe ? 300White0.00 ? 400Stone ?

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 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 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 Creating a sequential file After user enters end-of-file, the program closes the clients.dat with fclose and terminates.

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 Reading Data from Sequential File Output AccountNameBalance 100Jones Doe White Stone-42.16

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 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 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 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 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 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 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 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 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 Enter account number (1 to 100, 0 to end) ? 30 Enter lastname, firstname, balance ?Dunn Stacy 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 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 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 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 Reading Data Randomly from a Randomly Accessed File Output AcctLast NameFirst NameBalance 29 BrownNancy DunnStacey BarkerDoug0.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.