SlideShare a Scribd company logo
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
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
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
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
char c; 
clrscr ( ); 
printf (“data into nn”); 
f1=fopen (“input”,”w”); 
while ((c=getchar ()! =eof) 
putc(c, f1); 
fclose (f1); 
printf (“n data outputnn”); 
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
/*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
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 (“nn contents oof odd file:nn”); 
while ((num=getw (f2))! =eof) 
printf (“%4d”, num); 
printf (“nncontents of even file:nn”); 
while ((num=getw (f3))! =eof) 
printf (“%4d”, num); 
fclose (f2); 
fclose (f3); 
M V B REDDY GITAM UNIVERSITY BLR
} 
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
*/ 
#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
fscanf (fp,”%s%d%f%d”, item, &num, &price, &qty); 
value=price*qty; 
fprintf (stdout,”%s %d %f %d %fn”, 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
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
M V B REDDY GITAM UNIVERSITY BLR

More Related Content

DOCX
Understanding c file handling functions with examples
PPTX
Programming in C
PPTX
File handling in C by Faixan
PPTX
File in C language
PDF
Files in C
PPT
File handling in c
PPT
File handling-c programming language
PPTX
File Management in C
Understanding c file handling functions with examples
Programming in C
File handling in C by Faixan
File in C language
Files in C
File handling in c
File handling-c programming language
File Management in C

What's hot (19)

PPTX
File handling in C
PPTX
File handling in c
PPTX
File handling in C
PDF
File_Management_in_C
PPTX
C Programming Unit-5
PPTX
File handling in c
PPT
File Management
PDF
Module 03 File Handling in C
PPTX
File Management in C
PPT
File in c
PPTX
file management in c language
PPT
File in C Programming
PPTX
File management in C++
PPT
File handling in 'C'
PPSX
C programming file handling
PPT
File handling-dutt
PPT
PPTX
Programming in C
File handling in C
File handling in c
File handling in C
File_Management_in_C
C Programming Unit-5
File handling in c
File Management
Module 03 File Handling in C
File Management in C
File in c
file management in c language
File in C Programming
File management in C++
File handling in 'C'
C programming file handling
File handling-dutt
Programming in C
Ad

Similar to C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY (20)

PDF
File handling C program
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PPT
Unit5
PPTX
File management
PPT
file_handling_in_c.ppt
PDF
VIT351 Software Development VI Unit5
PPT
file_handling_in_c.ppt
PPTX
PPS PPT 2.pptx
PDF
Handout#01
PPT
Unit5 C
PPT
Lecture 20 - File Handling
PPTX
Data Structure Using C - FILES
DOCX
PPTX
File management
PPTX
Unit-VI.pptx
PPTX
want to learn files,then just use this ppt to learn
PDF
File Management
PDF
FILES IN C
PPSX
1file handling
PPTX
INput output stream in ccP Full Detail.pptx
File handling C program
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
Unit5
File management
file_handling_in_c.ppt
VIT351 Software Development VI Unit5
file_handling_in_c.ppt
PPS PPT 2.pptx
Handout#01
Unit5 C
Lecture 20 - File Handling
Data Structure Using C - FILES
File management
Unit-VI.pptx
want to learn files,then just use this ppt to learn
File Management
FILES IN C
1file handling
INput output stream in ccP Full Detail.pptx
Ad

Recently uploaded (20)

PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
DOCX
573137875-Attendance-Management-System-original
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPT
Project quality management in manufacturing
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Sustainable Sites - Green Building Construction
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Geodesy 1.pptx...............................................
PDF
Well-logging-methods_new................
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPT
Mechanical Engineering MATERIALS Selection
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
PPT on Performance Review to get promotions
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
OOP with Java - Java Introduction (Basics)
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Embodied AI: Ushering in the Next Era of Intelligent Systems
573137875-Attendance-Management-System-original
Arduino robotics embedded978-1-4302-3184-4.pdf
Project quality management in manufacturing
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Sustainable Sites - Green Building Construction
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Geodesy 1.pptx...............................................
Well-logging-methods_new................
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Mechanical Engineering MATERIALS Selection
UNIT 4 Total Quality Management .pptx
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT on Performance Review to get promotions
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
OOP with Java - Java Introduction (Basics)

C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

  • 1. 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
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. char c; clrscr ( ); printf (“data into nn”); f1=fopen (“input”,”w”); while ((c=getchar ()! =eof) putc(c, f1); fclose (f1); printf (“n data outputnn”); 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
  • 6. /*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
  • 7. 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 (“nn contents oof odd file:nn”); while ((num=getw (f2))! =eof) printf (“%4d”, num); printf (“nncontents of even file:nn”); while ((num=getw (f3))! =eof) printf (“%4d”, num); fclose (f2); fclose (f3); M V B REDDY GITAM UNIVERSITY BLR
  • 8. } 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
  • 9. */ #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
  • 10. fscanf (fp,”%s%d%f%d”, item, &num, &price, &qty); value=price*qty; fprintf (stdout,”%s %d %f %d %fn”, 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
  • 11. 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
  • 12. M V B REDDY GITAM UNIVERSITY BLR