1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.

Slides:



Advertisements
Similar presentations
File Management in C. What is a File? A file is a collection of related data that a computers treats as a single unit. Computers store files to secondary.
Advertisements

Files in C Rohit Khokher.
BITS Pilani, Pilani Campus TA C252 Computer Programming - II Vikas Singh File Handling.
File Management in C. A file is a collection of related data that a computers treats as a single unit. File is a collection of data stored permanently.
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.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students C File Input and Output Checking input for errors.
1 Structure part 1 & File Processing. 2 Structures.
20/03/01 Sudeshna Sarkar, CSE, IIT Kharagpur1 File Handling in C Lecture 17c 20/3/01.
File Handling Spring 2013Programming and Data Structure1.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 7P. 1Winter Quarter File I/O in C Lecture.
 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.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
1 Lecture09: File I/O 5/6/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
CSC 211 Data Structures Lecture 32
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.
CSEB114: Principle of programming Chapter 11: Data Files & File Processing.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
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.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
24-2 Perform File I/O using file pointers FILE * data-type Opening and closing files Character Input and Output String Input and Output Related Chapter:
chap8 Chapter 12 Files (reference: Deitel ’ s chap 11)
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
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.
Files A collection of related data treated as a unit. Two types Text
 2007 Pearson Education, Inc. All rights reserved. 1 C File Processing.
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 Computer Programming Lecture 15 Text File I/O Assist. Prof Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
1 Chapter 11 – File Processing Outline 11.1Introduction 11.2The Data Hierarchy 11.3Files and Streams 11.4Creating a Sequential Access File 11.5Reading.
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
 2007 Pearson Education, Inc. All rights reserved C File Processing.
UniMAP SemI-11/12EKT120: Computer Programming1 Files.
Chapter 11 – File Processing
11 C File Processing.
TMF1414 Introduction to Programming
EKT120: Computer Programming
CSE1320 Files in C Dr. Sajib Datta
CSE1320 Files in C Dr. Sajib Datta
Files I/O, Streams, I/O Redirection, Reading with fscanf
CSE1320 Files in C Dr. Sajib Datta
Chapter 11 – File Processing
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
FILE HANDLING IN C.
File Input and Output.
File Handling.
Fundamental of Programming (C)
File Handling in C.
EPSII 59:006 Spring 2004.
Chapter 11 Files chap8.
CSc 352 File I/O Saumya Debray Dept. of Computer Science
Files Chapter 8.
Presentation transcript:

1 CHAPTER6 CHAPTER 6

Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential access file 2

 Storage of data in variables and arrays is temporary-all such data are lost when a program terminates.  Files are used for permanent retention of large amounts of data.  Computers store files on secondary storage devices esp. disk storage devices.  A file is a group of related records.  A record is a group of related fields. 3

 C views a file as a sequential stream of bytes.  A file ends either with an EOF (end-of-file) marker or at a specified byte number specified by the system.  When a file is opened, a stream is associated with a file.  Streams provide communication channels between files and the programs n -1

 In addition to providing access to a file, a stream can also be used to access devices.  For example, when a program (any program) is executed, 3 streams are automatically opened: ◦ standard input (stdin)  enable the program to read data from keyboard ◦ standard output (stdout)  enable the program to print data on the screen ◦ standard error (stderr)  enable program to print errors on the screen  They are all manipulated using file pointers. 5

 The statement: FILE *fptr1, *fptr2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream.  Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable. 6

 They must be declared as file pointers.  They must be opened using an fopen function call, before processing.  The function feof can be used.  The files must be closed with an fclose function call.  Input function used – fscanf()  Output function used – fprintf()  Should use appropriate mode to file – w, r, a etc 7

 Opening a File  Reading data from a file  Writing data to a file  Closing a file 8

9 r - open for reading w - open for writing (file need not exist),if the file already exists, discard current contents a - open for appending (file need not exist), writing at the end of the file. If the file already exists, discard current contents r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite file) a+ - open for reading and writing (append if file exists), writing is done at the end of the file

10 The statement: fptr1 = fopen ( "mydata", "r" ) ; would open the file mydata for input (reading). The statement: fptr2 = fopen ("results", "w" ) ; would open the file results for output (writing). Once the files are open, they stay open until you close them or end the program (which will close all files.)

 If the file was not able to be opened, then the value returned by the fopen routine is NULL.  For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; } 11

 If an error occurs while opening a file (in which case fopen() returns a NULL), it could be due to any of these errors: ◦ Opening a non-existing file for reading ◦ Opening a file for reading or writing without having granted the appropriate access to the file by the operating system. ◦ Opening a file for writing when no disk space is available.  Always remember that the mode “w” will overwrite the current data in the file. When we want to update a file, always use the update mode r+” (but w/r from top) 12

 In the following segment of C language code: int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b. 13

 The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed.  There are a number of ways to test for the end-of-file condition. One is to use the feof function which returns a true or false condition: fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n”); }  There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n”) ; } 14

 Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2. Chapter 7: File Processing15

 The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory. 16

17 typedef struct { int roll; char dept_code[6]; float cgpa; } STUD; main() { FILE *stud; STUD s; float sum = 0.0; int count = 0; stud = fopen (“stud.dat”, “r”) ; while (1) { if (feof (stud)) break; fscanf (stud, “%d %s %f”, &s.roll, s.dept_code, &s.cgpa); count ++; sum += s.cgpa; } printf (“\nThe average cgpa is %f”, sum/count); fclose (stud); }

18 #include void main (void) { int account; char name[30]; float balance; FILE *fptr; if ((fptr = fopen("D:/clients.txt", "w")) == NULL) printf("Error: the file cannot be opened\n"); else { printf ("Enter the account #, name and balance or EOF to end input:\n"); scanf ("%d %s %f", &account, &name, &balance); while (!feof(stdin)) { fprintf(fptr, "%d %s %.2f\n", account, name, balance); scanf ("%d%s%f", &account, &name, &balance); } fclose (fptr); } Creating a Sequential Access File: Example 2

 Output from program that creates sequential access file Enter the account #, name and balance or EOF to end input: 111 sara hannah ruby arris Nufail Yasmin ^Z Press any key to continue 19 Creating a Sequential Access File cont…

 Content of “D:/client.txt”: 20 Creating a Sequential Access File cont…

21 #include void main (void) { int account; char name[30]; float balance; FILE *fptr; if ((fptr = fopen("D:/clients.txt", "r")) == NULL) printf("Error: the file cannot be opened\n"); else { printf ("%-10s%-13s%s\n", "Account", "Name", "Balance"); fscanf (fptr, "%d %s %f", &account, &name, &balance); while (!feof(fptr)) { printf ("%-10d%-13s%.2f\n", account, name, balance); fscanf (fptr, "%d %s %f", &account, &name, &balance); } fclose (fptr); } Reading Data from a Sequential Access File : Example 3

 if ((fptr = fopen("D:/clients.txt", "r")) == NULL) ◦ Attempts to open the file clients.txt for reading and determines whether the file is opened successfully. Notice that the mode used is “r”.  fscanf (fptr, "%d %s %f", &account, &name, &balance); ◦ Reads data from the file clients.txt ◦ Equivalent to function scanf() except that it receives as an argument a file pointer for the file from which the data is read. 22 Reading Data from a Sequential Access File cont…

 Output from program that reads data from sequential access file Account Name Balance 111 sara hannah ruby arris Nufail Yasmin Press any key to continue 23 Reading Data from a Sequential Access File cont…

#include void create_file (); int request, account; float balance; char name[30]; FILE *fptr; void main() { create_file(); if ((fptr = fopen("E:/LECTURE/FILE/test.txt", "r")) == NULL) printf("Error: the file cannot be opened\n"); else { printf("Enter request\n" "1 - List accounts with zero balances\n" "2 - List accounts with credit balances\n" "3 - List accounts with debit balances\n" "4 - End of run\nRequest #? "); scanf("%d", &request); 24

while(request!=4) { fscanf (fptr, "%d %s %f", &account, &name, &balance); switch(request){ case 1: printf("\nAccounts with zero balances:\n"); while (!feof(fptr)) { if( balance == 0 ) printf ("%-10d%-13s%.2f\n", account, name, balance); fscanf (fptr, "%d %s %f", &account, &name, &balance); } break; 25

case 2: printf("\nAccounts with credit balances:\n"); while (!feof(fptr)) { if( balance < 0 ) printf ("%-10d%-13s%.2f\n", account, name, balance); fscanf (fptr, "%d %s %f", &account, &name, &balance); } break; 26

case 3: printf("\nAccounts with debit balances:\n"); while (!feof(fptr)) { if( balance > 0 ) printf ("%-10d%-13s%.2f\n", account, name, balance); fscanf (fptr, "%d %s %f", &account, &name, &balance); } break; } /* End switch */ 27

rewind(fptr); /* return fptr to beginning of file */ printf("\nRequest #? "); scanf("%d", &request); } /* End while before switch */ printf("End of run.\n"); fclose(fptr); } /* End else */ } /* End main */ 28

void create_file () { if ((fptr = fopen("E:/LECTURE/FILE/test.txt", "a+")) == NULL) printf("Error: the file cannot be opened\n"); else { printf ("Enter the account #, name and balance or EOF to end input:\n"); scanf ("%d %s %f", &account, &name, &balance); while (!feof(stdin)) { fprintf(fptr, "%d %s %.2f\n", account, name, balance); scanf ("%d %s %f", &account, &name, &balance); } fclose (fptr); } 29

Enter request 1 - List accounts with zero balances 2 - List accounts with credit balances 3 - List accounts with debit balances 4 - End of run Request #? 1 Accounts with zero balances: 333 ruby

Request #? 2 Accounts with credit balances: 444 Arris Request #? 3 Accounts with debit balances: 111 sara hannah Nufail Yasmin

Request #? 4 End of run. Press any key to continue NOTE : You must create a sequential access file first, then it is up to you to use any possible mode to the file. 32

33 Associated commands are: fputc()-writes a char at a time to a file fputs() -writes a string to a file fprintf() - writes a variable number of items to an output stream fgetc() - reads a char from stream fgets() - reads from stream into array fscanf() - reads a variable number of items from stream feof - tests if file has reaches its end. Other File Functions

34 Summary FILE Concepts Steps on how to apply FILE programming structure Examples of FILE program