file-oriented input & output

36
Chapter 7 : File Processing 1 File-Oriented Input & Output CHAPTER 7

Upload: neila

Post on 18-Jan-2016

77 views

Category:

Documents


0 download

DESCRIPTION

File-Oriented Input & Output. CHAPTER 7. Chapter 7: File Processing. Objectives: You’ll learn about; Files and streams Creating a sequential access file Reading data from a sequential access file. Introduction. Storing data in variables (in memory) is just temporary. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: File-Oriented Input & Output

Chapter 7 : File Processing 1

File-Oriented Input & Output

CHAPTER 7

Page 2: File-Oriented Input & Output

Chapter 7: File Processing 2

Chapter 7: File Processing

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

file

Page 3: File-Oriented Input & Output

Chapter 7: File Processing 3

Introduction Storing data in variables (in memory) is

just temporary. such data lost when the 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.

Page 4: File-Oriented Input & Output

Chapter 7: File Processing 4

Files and Streams

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.

0 1 2 3 4 5 6 7 8 . . . . . n-1

Page 5: File-Oriented Input & Output

Chapter 7: File Processing 5

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.

Files and Streams cont…

Page 6: File-Oriented Input & Output

Files and Streams cont… The statement:

FILE *fptr1, *fptr2 ;declares fptr1 and fptr2 are pointer variables of type FILE. They will be assigned an 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.

Chapter 7: File Processing 6

Page 7: File-Oriented Input & Output

Chapter 7: File Processing 7

Fundamental of Data File (.txt) 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

Page 8: File-Oriented Input & Output

Basic File Operations Opening a File Reading data from a file Writing data to a file Closing a file

Chapter 7: File Processing 8

Page 9: File-Oriented Input & Output

Chapter 7: File Processing 9

Creating a Sequential AccessMode of Opening File

r - open for readingw - open for writing (file need not exist),if the file already exists, discard current contentsa - open for appending (file need not exist), writing at the end of the file. If the file already exists, discard current contentsr+ - open for reading and writing, start at beginningw+ - 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

Page 10: File-Oriented Input & Output

Chapter 7: File Processing 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, the file status is opening until you close them or end the program (which will close all files.)

Creating a Sequential Access File :

Opening Files

Page 11: File-Oriented Input & Output

Creating a Sequential Access File :

Testing for Successful Open If the file was not able to be opened, then the

value returned by the fopen function 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") ;

}Chapter 7: File Processing 11

Page 12: File-Oriented Input & Output

Chapter 7: File Processing 12

Page 13: File-Oriented Input & Output

Chapter 7: File Processing 13

Page 14: File-Oriented Input & Output

Chapter 7: File Processing 14

If an error occurs while opening a file (in which, fopen() returns 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 user.

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+”

Creating a Sequential Access File (con’t)

Page 15: File-Oriented Input & Output

Creating a Sequential Access File :

Reading From Files 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.

Chapter 7: File Processing 15

Page 16: File-Oriented Input & Output

Creating a Sequential Access File :

End of File 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”) ;}

Chapter 7: File Processing 16

Page 17: File-Oriented Input & Output

Creating a Sequential Access File :

Writing to Files 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 Processing 17

Page 18: File-Oriented Input & Output

Creating a Sequential Access File :

Closing Files The statements: 

fclose ( fptr1 ) ;fclose ( fptr2 ) ;

 will close the files and release the file descriptor space and I/O buffer memory.

Chapter 7: File Processing 18

Page 19: File-Oriented Input & Output

Creating a Sequential Access File :

Example 1

Chapter 7: File Processing 19

#include <stdio.h>#include <stdlib.h>

typedef struct { int roll; char dept_code[6]; float cgpa;} STUD;

int main() { FILE *stud; STUD s; float sum = 0.0; int count = 0; stud = fopen(“data.txt", "r"); if (!stud) { printf("File not exist."); exit(1); } 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); return (EXIT_SUCCESS);}

Page 20: File-Oriented Input & Output

Chapter 7: File Processing 20

#include <stdio.h>

int main(void) { int account; char name[30]; float balance; FILE *fptr; if ((fptr = fopen("clients.txt", "w")) == NULL) printf("Error: the file cannot be opened\n"); else { while (1) { printf("Enter the account #, name and balance (or enter -1 -1 -1 to quit) : \n"); scanf("%d %s %f", &account, &name, &balance); if (account == -1) break; fprintf(fptr, "%d %s %.2f\n", account, name, balance); } } fclose(fptr); return 0;}

Creating a Sequential Access File:

Example 2

Page 21: File-Oriented Input & Output

Chapter 7: File Processing 21

Creating a Sequential Access File cont…

Output from program that creates sequential access file

Enter the account #, name and balance (or enter -1 -1 -1 to quit) :111 sara 24.98222 hannah 345.67333 ruby 0.00444 arris -42.16555 Nufail 224.62666 Yasmin 987.90^ZPress any key to continue

Page 22: File-Oriented Input & Output

Chapter 7: File Processing 22

Content of “client.txt”:

Creating a Sequential Access File cont…

Page 23: File-Oriented Input & Output

Chapter 7: File Processing 23

#include <stdio.h>

void main(void) { int account; char name[30]; float balance; FILE *fptr; if ((fptr = fopen("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

Page 24: File-Oriented Input & Output

Chapter 7: File Processing 24

if ((fptr = fopen("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.

Reading Data from a Sequential Access File cont…

Page 25: File-Oriented Input & Output

Chapter 7: File Processing 25

Output from program that reads data from sequential access file

Account Name Balance111 sara 24.98222 hannah 345.67333 ruby 0.00444 arris -42.16555 Nufail 224.62666 Yasmin 987.90Press any key to continue

Reading Data from a Sequential Access File cont…

Page 26: File-Oriented Input & Output

Chapter 7: File Processing 26

Complete credit inquiry program: Example 4

#include<stdio.h>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);

Page 27: File-Oriented Input & Output

Chapter 7: File Processing 27

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;

Complete credit inquiry program cont…

Page 28: File-Oriented Input & Output

Chapter 7: File Processing 28

Complete credit inquiry program cont…

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;

Page 29: File-Oriented Input & Output

Chapter 7: File Processing 29

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 */

Complete credit inquiry program cont…

Page 30: File-Oriented Input & Output

Chapter 7: File Processing 30

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 */

Complete credit inquiry program cont…

Page 31: File-Oriented Input & Output

Chapter 7: File Processing 31

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);}

Complete credit inquiry program cont…

Page 32: File-Oriented Input & Output

Chapter 7: File Processing 32

Output

Enter request1 - List accounts with zero balances2 - List accounts with credit balances3 - List accounts with debit balances4 - End of runRequest #? 1

Accounts with zero balances:333 ruby 0.00

Page 33: File-Oriented Input & Output

Chapter 7: File Processing 33

Request #? 2

Accounts with credit balances:444 Arris -42.16

Request #? 3

Accounts with debit balances:111 sara 24.98222 hannah 345.67555 Nufail 224.62666 Yasmin 987.90

Complete credit inquiry program cont…

Page 34: File-Oriented Input & Output

Chapter 7: File Processing 34

Request #? 4End of run.Press any key to continue

Complete credit inquiry program cont…

Page 35: File-Oriented Input & Output

Chapter 7: File Processing 35

fputc() -writes a char at a time to a filefputs() -writes a string to a filefprintf() – writes variable value an output streamfgetc() - reads a char from streamfgets() - reads from stream into arrayfscanf() – reads variable value from streamfeof - tests if file has reaches its end.

Other File Functions

Page 36: File-Oriented Input & Output

Chapter 7: File Processing 36

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