C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

13
UNIT-V INPUT AND OUTPUT: UNIT-V Objective: Files handles large amounts of data as before it became cumbersome and time consuming to handle large volumes of data through terminals. The entire data is lost when either the program is terminated or the computer is turned off. Thus the files drives away all of those limitations of using ordinary data. Hence here in this unit we will learn about the handling of files. INTRODUCTION: Till now we have been using the functions such that scanf and printf to read and print data. There are console Oriented I/O functions which always use the terminals (Key board and monitor) as the target place. This works fine as long as the data is small. However many real life problems involves large volume of data and in such situations the console oriented I/O operations pose two major problems. 1. It becomes cumbersome and time consuming to handle large volume of data through terminal. M V B REDDY GITAM UNIVERSITY BLR

Transcript of C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

Page 1: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

UNIT-V

INPUT AND OUTPUT:UNIT-V

Objective:

Files handles large amounts of data as before it became cumbersome and time

consuming to handle large volumes of data through terminals. The entire data is lost when either

the program is terminated or the computer is turned off. Thus the files drives away all of those

limitations of using ordinary data. Hence here in this unit we will learn about the handling of

files.

INTRODUCTION:

Till now we have been using the functions such that scanf and printf to read and print data.

There are console Oriented I/O functions which always use the terminals (Key board and monitor) as the

target place. This works fine as long as the data is small. However many real life problems involves large

volume of data and in such situations the console oriented I/O operations pose two major problems.

1. It becomes cumbersome and time consuming to handle large volume of data through terminal.

2. The entire data is lost when the program is terminated or the computer is turned off.

It is therefore necessary to have amore flexible approach where data can be stored on the disk

and read whenever necessary, without destroying the data. This method employs the concept of file to

store data. A file is a place on the disk where a group of related data is stored. Like most other language

C supports a number of functions that have the ability to perform basic file operations.

FILE OPERATIONS:

1. Naming a file

2. Opening a file

3. Reading data from a file

M V B REDDY GITAM UNIVERSITY BLR

Page 2: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

4. Writing data to the file

5. Closing a file

There are two distinct ways to perform the file operations in C. The first one is known as the low

level I/O and uses UNIX system calls. The second method is referred to as the high level I/O operations

and uses functions in C’s standard I/O library.

DEFINING AND OPENING A FILE:

If we want to store data in a file in the secondary memory, we must specify certain things about

the file, to the operating system. They include

1. Filename

2. Data structure

3. Purpose

Filename is a string of characters that make up a valid filename. Data structure of a file is defined

as FILE in the library of standard I/O function definition. Therefore all files should be declared as type

before they are used. FILE is a defined data type.

When we open a file we must specify what we want to do with the file. For example we may

write data to the file or read the already existing data.

THE GENERAL FORMATE FOR DECLARING AND OPENING A FILE:

FILE *fp;

fp = fopen(“filename”,mode);

The first statement declares the variable fp as a pointer to the data type FILE. The second statement

opens the file, named file name and assigns an identifier to the FILE type pointer fp. This pointer which

contains all the information about the file is subsequently used as a communication link between the

system and the program.

The second statement also specifies the purpose of opening this file. The mode does this job. Mode

can be one of the following

r opening the file for reading only.

M V B REDDY GITAM UNIVERSITY BLR

Page 3: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

w opening the file for writing only

a opening the file for appending (or adding) data to it.

Both the filename and mode are specified as string. They should be enclosed in double quotation

marks.

When trying to open the file of the following things may happen,

1. When the mode is writing a file with the specified name is created if the file does not exist. The

contents are deleted if the file already exist

2. When the purpose is appending the file is opened with the current contents safe. A file with the

specified name is created if the file does not exist.

3. If the purpose is reading and if it exists then the file is opened with the current contents safe.

Otherwise an error occurs.

Many recent compilers include additional modes of operations they are:

r+ The existing file is opened to the beginning for both reading & writing.

w+ same as w except both for reading & writing.

a+ Same as a except both for reading & writing.

CLOSING A FILE: A file must be closed as soon as all operations on it have been completed. We have to

close a file is when we want to reopen the same file in a different mode. The I/O library supports the

functions to do this

fclose (file_pointer)

EX: FILE *x1,*x2;

x1 = fopen(“salary”,r);

x2 = fopen(“employee”,w);

………

………..

………..

M V B REDDY GITAM UNIVERSITY BLR

Page 4: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

fclose (x1);

fclose (x2);

All files are closed automatically whenever a program terminates. However closing a file as soon

as you are done with it is good programming habit.

INPUT/OUTPUT OPERATIONS ON FILES:

The getc and putc functions: the simplest file i/o functions are getc and putc.these are

analogous to getchar and putchar functions and handle one character at a time. Assume that a file is

opened with mode W and file pointer fp then the statement is

Putc(c, fp);

Writes the character contained in the character variable c to the file associated with file

pointer,fp.

.

similarly getc is used to read a character from a file that has been opened in read mode, the statement

is

C= getc(fp);

The file pointer moves by one character position for every operation of getc or putc. The getc

will return an end-of-file marker EOF, when end of the file has been reached. Therefore the reading

should be terminated when EOF is encountered.

EX:

/*write a program to read data form the keyboard , write it to a file called INPUT , again reqad the

same data form the INPUT file and display it on the screen*/

#include<stdio.h>

main ( )

{

file *f1;

M V B REDDY GITAM UNIVERSITY BLR

Page 5: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

char c;

clrscr ( );

printf (“data into \n\n”);

f1=fopen (“input”,”w”);

while ((c=getchar ()! =eof)

putc(c, f1);

fclose (f1);

printf (“\n data output\n\n”);

f1=fopen (“input”,”r”);

while ((c=getc (f1))! =eof)

printf (“%c”, c);

fclose (f1);

THE GETW AND PUTW FUNCTIONS:

The getw and putw are integer oriented functions. they are similar the getc and putc functions, are used

to read and write integer values. These functions would be useful when we deal with only integer data.

The general form is

Putw (integer, fp);

Getw (fp);

EX:

M V B REDDY GITAM UNIVERSITY BLR

Page 6: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

/*A file name DATA contains a series of integer numbers. Code a program to read these numbers and

then write all the odd numbers to the file to be called ODD and all even numbers to a file to be called

EVEN.*/

#include<stdio.h>

main ( )

{

file *f1,*f2,*f3;

int num, i;

clrscr ( );

printf (“contents of data file:\n”);

f1=fopen (“data”,”w”);

for (i=1;i<=30;i ++)

{

scanf (“%d”, &num);

if (num==-1)

break;

putw (num, f1);

}

fclose (f1);

f1=fopen (“data”,”r”);

M V B REDDY GITAM UNIVERSITY BLR

Page 7: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

f2=fopen (“odd”,”w”);

f3=fopen (“even”,”w”);

while (num==getw (f1))! =eof)

{

if (num%2= =0)

putw (num, f3);

else

putw (num, f2);

}

fclose (f1);

fclose (f2);

fclose (f3);

f2=fopen (“odd”,”r”);

f3=fopen (“even”,”r”);

printf (“\n\n contents oof odd file:\n\n”);

while ((num=getw (f2))! =eof)

printf (“%4d”, num);

printf (“\n\ncontents of even file:\n\n”);

while ((num=getw (f3))! =eof)

printf (“%4d”, num);

fclose (f2);

fclose (f3);

M V B REDDY GITAM UNIVERSITY BLR

Page 8: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

}

THE FPRINTF AND FSCANF FUNCTIONS:

So far we have seen functions which can handle only one character or integer at a time. Most

of the compilers support two other functions namely fprintf and fscanf functions that can handle a

group of mixed data simultaneously.

The functions fprintf and fscanf perform I/O operations that are identical to the familiar printf

and scanf functions .The first argument of these function is a filepointer which specifies file to be used.

THE GENERAL FORM OF PRINTF IS:

fprintf (fp,”control string”, list);

The list may include variables, constants and strings.

EX:

THE GENERAL FORM OF FSCANF IS:

fscanf (f1,”%d%f”, &age, &sal);

EX:/*WRITE A PROGRAM TO OPEN A FILE NAMED “INVENTORY” AND STORE IT THE FOLLOWING DATA*/

Item name number price quantity

IV 111 25000.75 15

VCP 113 42000.00 3

VCR 123 50000.35 10

Extend the program to read this data from the file INVENTORY and display the inventory table

with the value of each item.

M V B REDDY GITAM UNIVERSITY BLR

Page 9: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

*/

#include<stdio.h>

main ( )

{

file *fp;

int num, qty, i;

float price, value;

char item [10], filename [20];

printf (“enter the name”);

scanf (“%s”, filename);

fp=fopen (filename,”w”);

printf (“input inventory data”);

printf (“itemname number price quantity”);

for (i=1; i<=3; i ++)

fscanf (stdin.”%s%d%f%d”, item, &num, &price, &qty);

fclose (fp);

fprintf (stdout,”\n”);

fp=fopen (filename,”r”);

printf (“itemname number price quantity value”);

for (i=1; i< =3; i++)

{

M V B REDDY GITAM UNIVERSITY BLR

Page 10: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

fscanf (fp,”%s%d%f%d”, item, &num, &price, &qty);

value=price*qty;

fprintf (stdout,”%s %d %f %d %f\n”, item, num, price, qty, value);

}

fclose (fp);

}

Key points to remember:

We should not read beyond the end of the file mark.

We should not try to use a file that has not been opened.

We should not perform a operation on a file, when the file is opened for another type of

operation.

Sample theory questions:

1) Describe the use of getc and putc functions?

2) What are the common uses of rewind and ftell functions?

3) Distinguish between the following functions?

a) getc and getn.

b) printf and fprintf.

c) feof and ferror.

4) Write a program to copy the content of one file into another?

M V B REDDY GITAM UNIVERSITY BLR

Page 11: C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

Sample objective questions:

1) fopen() is the function name that creates a new file for use.

2) fopen() is the function name that opens an existing file for use.

3) getc() is the function that reads a character from the file.

4) fscanf() reads a set of values from a file.

5) ftell() function gives the current position in the file.

M V B REDDY GITAM UNIVERSITY BLR