SlideShare une entreprise Scribd logo
1  sur  12
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

Contenu connexe

Tendances (19)

File handling in C
File handling in CFile handling in C
File handling in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File_Management_in_C
File_Management_in_CFile_Management_in_C
File_Management_in_C
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File Management
File ManagementFile Management
File Management
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File in c
File in cFile in c
File in c
 
File operations in c
File operations in cFile operations in c
File operations in c
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
File management in C++
File management in C++File management in C++
File management in C++
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Programming in C
Programming in CProgramming in C
Programming in C
 

Similaire à C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY

Similaire à C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY (20)

File handling C program
File handling C programFile handling C program
File handling C program
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Unit5
Unit5Unit5
Unit5
 
File management
File managementFile management
File management
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Handout#01
Handout#01Handout#01
Handout#01
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Lecture 20 - File Handling
Lecture 20 - File HandlingLecture 20 - File Handling
Lecture 20 - File Handling
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Unit 8
Unit 8Unit 8
Unit 8
 
File management
File managementFile management
File management
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File Management
File ManagementFile Management
File Management
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
1file handling
1file handling1file handling
1file handling
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
Programming in C
Programming in CProgramming in C
Programming in C
 

Dernier

Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086anil_gaur
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxJuliansyahHarahap1
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 

Dernier (20)

Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 

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