SlideShare a Scribd company logo
File Handling in C
1
File:
• A file a collection of data stored in one unit, identified by filename.
• The primary purpose of a file is to keep record of data and record is the
group of related fields.
• Each file ends with an end of file(EOF) at a specified byte number, recorded
in FILE structure.
• A file must first be opened properly before it can be accessed for reading or
writing. When a file is opened an object(buffer) is created and a file is
associated with the buffer.
• In general, file is a collection of related records such as student’s name, date
of birth, address, marks, phone number etc.
• A file is nothing but a source of storing information permanently in the form
of a sequence of bytes on a disk.
2
Buffer:
When the computer reads, the data move from the external device to
memory and when it writes, the data move from memory to the external
device. This data movement often uses a special work area known as
buffer.
•A buffer is a temporary storage area that holds data while they are
being transferred to or from memory.
•The primary purpose of a buffer is to synchronize the physical devices
with a program’s need.
3
File Handling:
•File handling is the process of storing data in the form of input or
output produced by running C programs in data file for future
reference and analysis. And, we can extract/fetch data from a file to
work with it in the program.
•File handling provides a mechanism to store the output of a program in
a file and to perform various operations on it.
•File handling concept provides various operations like creating a file,
opening a file, reading a file or manipulating data inside a file etc.
4
Why file handling?
•The data stored in the various of a program will be lost once the
program is terminated because they are stored in the Random Access
Memory(RAM) which is volatile memory.
•So, if we want store that data(input/output) used in the program
permanently inside the secondary storage device so that, we can access
these data from there whenever it is needed file handling concept is
important.
5
Block diagram of file accessing using a various function
written to a file and read from a file using various functions:
6
Types of file:
There are two types of file namely:
1. Text file
2. Binary file
3. Text file:
• These are the simplest files a user can create when dealing with file handling in C.
• It is created with a .txt extension using any simple text editor.
• A text file stores information in the form of ASCII characters internally, but when
you open the text file, you would find the content of the text readable to humans.
• Text file consume large storage space.
• Example: new.txt, file.c etc.
7
2. Binary file:
•A binary file stores information in the form of the binary number
system (0’s and 1’s) and hence occupies less storage space.
•In simple words, it stores information in the same way as the
information is held in computer memory. Therefore, it proves to be
much easier to access.
•Example: file.dat, photo.jpg, one.png, song.mp3, file.exe etc.
8
Difference between Text File and Binary File :-
Text File Binary File
1. Output Formatted Text. 1. Output in 0 and 1 binary format.
2. EOF(End of File), n(New Line) are used. 2. Binary mode not use such character.
3. fgetc ( ), fputc ( ), fprintf ( ), fscanf ( ), fgets (
), fputs ( ) are used.
3. fread ( ) and fwrite ( ) functions are
commonly used.
4. Numbers are stored as string. 4. Numbers are stored as int, float etc.
5. Takes more access time. 5. Takes less access time.
6. It occupies more memory than binary file. 6. It occupies less memory than text file.
9
Operations on File:
•Creating of a new File
•Opening an existing File
•Reading from a File
•Write to a File
•Moving to a specific location in a file
•Closing a File
10
File Operation Modes:
The different file mode that can be used in opening file are:
Mode Description
ā€œwā€ (write)
If the file doesn't exist then this mode creates a new file for writing, and if the file already exists then
the previous data is erased and the new data entered is written to the file.
ā€œrā€ (read)
This mode is used for opening an existing file for reading purpose only. The file to be opened must
exist and the previous data of the file is not erased.
ā€œaā€ (append)
If the file doesn't exist then this mode creates a new file and if the file already exists then the new data
entered is appended at the end of existing data. In this mode, the data existing in the file is not erased as
in ā€œwā€ mode.
ā€œw+ā€ (write + read)
This mode is same as ā€œwā€ mode but in this mode we can also read and modify the data. If the file
doesn't exist then a new file is created and if the file exists then previous data is erased.
ā€œr+ā€ (read + write)
This mode is same as ā€œrā€ mode but in this mode we can also write and modify existing data. The file to
be opened must exist and the previous data of file is not erased. Since we can add new data and modify
existing data so this mode is also called update mode.
ā€œa+ā€ (append + read)
This mode is same as the ā€œaā€ mode but in this mode we can also read the data stored in the file. If the
file doesn't exist, a new file is created and if the file already exists then new data is appended at the end
of existing data. We cannot modify existing data in this mode. 11
File Operation Modes:
Continue…
Mode Description
ā€œwbā€ Binary file opened in write mode.
ā€œabā€ Binary file opened in append mode.
ā€œrbā€ Binary file opened in read mode.
ā€œwb+ā€ Create a binary file for read/write.
ā€œrb+ā€ Open a binary file for read/write.
ā€œab+ā€ Append a binary file for read/write.
12
Text mode
• In text mode every digit or text are stored as a character and while reading
the content back, the conversion is required from character to appropriate
format and takes lots of space.
• Character I/O, string I/O, and formatted I/O use text mode.
• If 3.14159 is stored in character mode file size would be 8 bytes (counts
each character including decimal and EOF).
Binary mode
• In binary mode every digit or text is stored in binary format and while
reading the content no conversion is necessary and takes little space.
• fread ( ) and fwrite ( ) are used in binary mode.
• If 3.14159 is stored in character mode file size would be 4 bytes.
13
Opening a file:
• A file must be opened before any I/O operations performed on that file. The
process of establishing a connection between the program and file is called
opening the file.
• A structure named FILE is defined in the file <stdio.h> that contains all
information about the file like name, status, buffer size, current position, end of
file status etc.
• All these details are hidden from the programming and the operating system
takes care of all these things.
• A file pointer is a pointer to a structure of type FILE.
• Whenever a file is opened, a structure of type FILE is associated with it and a
file pointer that points to this structure identifies this file.
• Example: FILE *fp;
• The function fopen ( ) is used to open a file.
• Syntax: fp=fopen(ā€œpath:filename.extā€, ā€œfile_operation_modeā€);
14
Closing a file:
• The file that was opened using fopen ( ) function must be closed when no
more operations are to be performed on it.
• After closing the file, connection between file and program is broken.
• On closing the file, all the buffers associated with it are flushed i.e all the
data that is in the buffer is written to the file.
• The buffers allocated by the system for the files are freed after the file is
closed, so that these buffers can be available for other files.
• Although all the files are closed automatically when the program terminates,
but sometimes it may be necessary to close the file by using fclose( )
function.
• Syntax: fclose(name_of_file_pointer);
• Example: fclose(fp);
15
End of file (EOF):
•The file reading function need to know the end of file so that they can
stop reading.
•When the end of file is reached, the operating system sends an
end-of-file signal to the program.
•When the program receives this signal, the file reading function
returns EOF, which is a constant defined in the file <stdio.h> and its
value is -1.
•This is only applicable to text mode file only.
16
File Processing Techniques:
The approach to read or to write the content from/to the file is know as file
processing. There are basically two types of file processing techniques
namely:
1. Sequential file processing:
In this type of files data is kept in sequential order if we want to read the last
record of the file, we need to read all records before that record so it takes
more time.
2. Random file processing:
In this type of files data can be read and modified randomly .If we want to
read the last record we can read it directly. It takes less time when compared
to sequential file.
17
Input/output Functions:
The functions used for file input/output are
1. Character I/O
fputc( ) :
•This function writes a character to the specified file at the current file
position and then increments the file position pointer.
•Syntax: fputc(character,file_pointer);
fgetc( ) :
•This function reads a single character from a given file and increments
the file pointer.
•Syntax: fgetc(file_pointer);
18
2. Integer I/O:
putw( ):
•This function writes an integer value to the file pointed to by file
pointer.
•Syntax: putw(Integer,file_pointer);
getw( ):
•This function returns the integer value from the file associated with
file pointer.
•Syntax: getw(file_pointer);
19
3. String I/O:
fputs():
•This function writes the null terminated string pointed by given
character pointer to a file.
•Syntax: fputs(string,file_pointer);
fgets():
•This function is used to read characters from a file and these characters
are stored in the string pointed by a character pointer.
•Syntax: fgets(string,length_of_string,file_pointer);
20
Formatted Input/output Functions:
fprintf( )
-This function is same as the printf( ) function but it writes
formatted data into the file instead of the standard
output(screen).
-This function has same parameters as in printf( ) but it has one
additional parameter which is a pointer of FILE type, that
points to the file to which the output is to be written.
Syntax: fprintf( fp, ā€œcontrol_stringā€,list of variables);
21
Example: Program used to write name, roll no and marks of student using fprintf
function.
int main()
{
FILE *fp;
char name[20];
int rollno;
float marks;
fp=fopen("std.txt","w");
if(fp==NULL)
{
printf("File can not open.");
}
printf("Enter Name: ");
gets(name);
printf("Enter roll.no: ");
scanf("%d",&rollno);
printf("Enter marks: ");
scanf("%f",&marks);
printf("Now writing data into file.....");
fprintf(fp,ā€œName=%snRoll.no=%dnMarks=%.1f",
name,rollno,marks);
fclose(fp);
getch();
return 0;
}
22
fscanf( )
- This function is similar to the scanf( ) function but it
reads data from file instead of standard input, so it has
one more parameter which is a pointer of FILE type and
it points to the file from which data will be read.
Syntax: fscanf( fp, ā€œcontrol_stringā€, &list_of_variables);
23
Example: Program to read data from a file using fscanf function.
int main()
{
FILE *fp;
char name[20];
int rollno;
float marks;
fp=fopen("std.txt","r");
if(fp==NULL)
{
printf("File can not open.");
}
fscanf(fp,"%s %d %f",name,&rollno,&marks);
printf("%s %d %.1f",name,rollno,marks);
fclose(fp);
}
24
Random access in a file:
•Random access means you can move to any part of a file and read or
write data from it without having to read through the entire file.
•In this technique the content are stored sequentially and read back the
content from any position of the file. And it can be performed using
some function like
1. fseek( )
2. rewind( )
3. ftell( )
25
1. fseek ( ):
• This function is used to move file position to a desired location within a file.
• Syntax: int fseek(fp, long int offset, int position);
- where, fp is a file pointer of type FILE which identifies the file.
- The offset specifies the number of positions(bytes) to be moved
from the location specified by position.
- The offset may be positive means move forward or negative means move
backwards.
- The value of the positon may be 0 or 1 or 2.
Value Constant Meaning
0 SEEK_SET Beginning of the file
1 SEEK_CUR Current position
2 SEEK_END End of the file
26
Continue…
Function Meaning
fseek(fp,n,SEEK_CUR) Set file position ahead from the current position
by n bytes.
fseek(fp,-n,SEEK_CUR) Set file position back from the current position
by n bytes.
fseek(fp,0,SEEK_END) Set file position to the end of the file.
fseek(fp,0,SEEK_SET) Set file position to the beginning of the file.
27
//Example of fseek( ):
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char str[30];
fp=fopen("abc.txt","r");
if(fp==NULL)
{
printf("File can not open.");
}
else
{
fgets(str,29,fp);
printf("%sn",str);
fseek(fp,3,SEEK_SET);
fgets(str,29,fp);
printf("%sn",str);
fseek(fp,-3,SEEK_CUR);
fgets(str,29,fp);
printf("%sn",str);
fseek(fp,-4,SEEK_END);
fgets(str,29,fp);
printf("%s",str);
}
getch();
}
28
2. ftell ( ):
•This function is used to get the current position of the file pointer.
•Syntax: int ftell(FILE *fp);
- This function will return the relative offset(bytes) of the current
position and fp is the file pointer.
- This function will tell us that how many bytes already been read
or written.
29
//Example of ftell( ):
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char str[30];
fp=fopen("abc.txt","r");
if(fp==NULL)
{
printf("File can not open.");
}
else
{
fseek(fp,-3,SEEK_END);
int n=ftell(fp);
printf("Current position of the file pointer is %d",n);
}
getch();
}
30
3. rewind ( ):
•This function is used to set the file pointer at the beginning of the file.
•Syntax: void rewind(FILE *fp);
- Where, fp is the file pointer which identify the file.
31
Example of rewind( ):
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char str[30];
fp=fopen("abc.txt","r");
if(fp==NULL)
{
printf("File can not open.");
}
else
{
fseek(fp,-3,SEEK_END);
rewind(fp);
int n=ftell(fp);
printf("Current position of the file pointer is %d",n);
}
getch();
}
32
Deleting a File:
- We use remove () to delete a file.
Syntax: remove( ā€œfile_nameā€);
Example:
int main()
{
remove("std.txt");
printf("Your file is successfully deleted.");
getch();
return 0;
}
33
Renaming a File:
-We use rename ( ) to rename a file.
Syntax: rename(ā€œexisting_file_nameā€, ā€œnew_file_nameā€);
Example:
int main()
{
rename("std.txt","std1.txt");
printf("Your file is renamed successfully.");
getch();
return 0;
}
34
Error Handling in Files:
• It is possible that an error may occur during I/O operations on a file.
• It is quite common that errors may occur while reading data from a file in C or
writing data to a file. For example, an error may arise due to the following:
- A file is opened with an Invalid name.
- When the data accessed is beyond the EOF character from the file.
- When a file is opened for one purpose but trying to perform different
operations.
- When a hidden file is trying to open then we can also get an error.
- If the file is write protected then also we can get an error.
- To handle these type of error, C provides error handling functions and
these are:
1. feof ( )
2. ferror ( )
35
1. feof ( ):
• This function is used to detect the end of file (eof) character in the file.
• This function returns non-zero if file pointer is on EOF otherwise it returns 0.
• Syntax: feof(file pointer variable);
• Example: feof(fp);
2. ferror ( ):
• This function is used to detect the errors while reading from the file or writing
into the file.
• It returns a non-zero value when an error is occurred while performing read
and write operations otherwise it returns zero.
• Syntax: ferror(file pointer variable);
• Example: ferror(fp);
36
fgetc() or getc(), fgets() and fscanf(): These
functions are input functions which read formatted
or unformatted data from the file.
fputc() or putc(), fputs() and fprintf(): These
functions are output functions which write
formatted or unformatted data to the file.
These functions are not suitable for reading or
writing large amount of data ( block of data)
to/from a file. So we use two additional functions:
1. fwrite()
2. fread()
37
1. fwrite ( ):
- Used to write block or record (fixed length group of data) of data to a file.
A record may be an array or a structure.
Syntax: fwrite( ptr, int size, int n, FILE *fp );
Where,
ptr : ptr is the reference (address) of an array or a structure stored in
memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
fp : fp is a file pointer where the records will be written in binary mode.
38
Example of fwrite ():
#include<stdio.h>
#include<conio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
int main()
{
FILE *fp;
char ch;
struct Student S;
fp = fopen("Student.txt","w");
if(fp == NULL)
{
printf("nFile Can't open.");
}
do
{
printf("Enter Roll : ");
scanf("%d",&S.roll);
printf("Enter Name : ");
scanf("%s",S.name);
printf("Enter Marks : ");
scanf("%f",&S.marks);
fwrite(&S,sizeof(S),1,fp);
printf("nDo you want to add
another data (y/n):n ");
ch = getche();
}while(ch=='y' || ch=='Y');
printf("nData written successfully...");
fclose(fp);
getch();
return 0;
}
39
2. fread ( ):
-Used to read block or record (fixed length group of data) of data
from a file.
Syntax: fread( ptr, int size, int n, FILE *fp );
Where,
ptr : ptr is the reference of an array or a structure where data will be stored
after reading.
size : size is the total number of bytes to be read from file.
n : is number of times a record will be read.
fp: fp is a file pointer from where the records will be read.
40
Example of fread():
#include<stdio.h>
#include<conio.h>
struct Student
{
char name[25];
int roll;
float marks;
};
int main()
{
FILE *fp;
struct Student S;
fp = fopen("Student.txt","r");
if(fp == NULL)
{
printf("File Can't open.");
}
fread(&S,sizeof(S),1,fp);
printf("Name=%sn",S.name);
printf("Roll NO=%dn",S.roll);
printf("Marks=%.1fn",S.marks);
fclose(fp);
getch();
return 0;
}
41
Simple Example of append mode:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
FILE *fp;
int i;
char ch[50]={"Kathmandu BernHardt"};
fp=fopen("new.txt","a");
if(fp==NULL)
{
printf("File can not open.");
}
for(i=0;i<strlen(ch);i++)
{
fputc(ch[i],fp);
}
fclose(fp);
getch();
return 0;
}
42
Q. Given a text file, create another text file deleting the following words
ā€œthreeā€, ā€œbadā€ and ā€œtimeā€.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
FILE *fp, *fpp;
Char C[10];
fp=fopen(ā€œfile.txtā€, ā€œrā€);
if(fp==NULL)
{
printf(ā€œFile Can not open.ā€);
}
fpp=fopen(ā€œtext.txtā€, ā€œwā€);
if(fpp==NULL)
{
printf(ā€œFile can not open.ā€);
}
While(fscanf(fp, ā€œ%sā€, &c)!=EOF)
{
if(((strcmp(c,ā€threeā€)!=0 && (strcmp(c,ā€badā€)!=0 && (strcmp(c,
ā€œtimeā€)!=0))
{
fprintf(fpp, ā€œ%sā€,c);
}
fclose(fp);
fclose(fpp);
getch();
return 0;
}
43

More Related Content

PPTX
Social Entrepreneurship
Ā 
PDF
Robert Frost presentation
PPTX
Pumping lemma Theory Of Automata
DOC
Notes of c programming 1st unit BCA I SEM
PPTX
Diabetes Mellitus
PPTX
Hypertension
PPTX
Republic Act No. 11313 Safe Spaces Act (Bawal Bastos Law).pptx
PPTX
Power Point Presentation on Artificial Intelligence
Social Entrepreneurship
Ā 
Robert Frost presentation
Pumping lemma Theory Of Automata
Notes of c programming 1st unit BCA I SEM
Diabetes Mellitus
Hypertension
Republic Act No. 11313 Safe Spaces Act (Bawal Bastos Law).pptx
Power Point Presentation on Artificial Intelligence

What's hot (20)

PPT
File handling in C++
PPTX
Php operators
PPTX
Basic HTML
PPTX
Python-FileHandling.pptx
PPTX
Html images syntax
PPTX
PPT
Python
PPTX
Functions in C
PPTX
EXCEPTION HANDLING IN PYTHON For students .py.pptx
PPT
Taking User Input in Java
PPT
Flow of Control
PPTX
File in C language
PPTX
Data file handling in c++
PPTX
JSON, XML and Data Science introduction.pptx
PPTX
Html media
PPSX
Html introduction
PDF
Python functions
PDF
Arrays In C
PPTX
Php basics
File handling in C++
Php operators
Basic HTML
Python-FileHandling.pptx
Html images syntax
Python
Functions in C
EXCEPTION HANDLING IN PYTHON For students .py.pptx
Taking User Input in Java
Flow of Control
File in C language
Data file handling in c++
JSON, XML and Data Science introduction.pptx
Html media
Html introduction
Python functions
Arrays In C
Php basics
Ad

Similar to Unit 5 File handling in C programming.pdf (20)

PPTX
File Handling.pptx
PPTX
File Handling
PPTX
File Handling
PPTX
File handing in C
PDF
file_c.pdf
PPTX
03-01-File Handling python.pptx
Ā 
PPTX
files concept in c program which is very use full
PPTX
5-filehandling-2004054567151830 (1).pptx
PPTX
File management
PDF
File handling and Dictionaries in python
PPTX
Chapter - 5.pptx
PDF
Python file handling
PPTX
Working with files in c++. file handling
PDF
637225560972186380.pdf
PPTX
File handling in C by Faixan
PDF
23CS101T PSPP python program - UNIT 5.pdf
PPTX
Unit V.pptx
PDF
chapter-4-data-file-handlingeng.pdf
PPTX
File handling in C hhsjsjshsjjsjsjs.pptx
PPTX
WjkjkjkjkjiohuhuhiuhkhiuhkjjjjjjjjjjK-12-13-file.pptx
File Handling.pptx
File Handling
File Handling
File handing in C
file_c.pdf
03-01-File Handling python.pptx
Ā 
files concept in c program which is very use full
5-filehandling-2004054567151830 (1).pptx
File management
File handling and Dictionaries in python
Chapter - 5.pptx
Python file handling
Working with files in c++. file handling
637225560972186380.pdf
File handling in C by Faixan
23CS101T PSPP python program - UNIT 5.pdf
Unit V.pptx
chapter-4-data-file-handlingeng.pdf
File handling in C hhsjsjshsjjsjsjs.pptx
WjkjkjkjkjiohuhuhiuhkhiuhkjjjjjjjjjjK-12-13-file.pptx
Ad

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
BƀI Tįŗ¬P Bį»” TRỢ 4 KỸ NĂNG TIįŗ¾NG ANH 9 GLOBAL SUCCESS - Cįŗ¢ NĂM - BƁM SƁT FORM Đ...
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
Ā 
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Classroom Observation Tools for Teachers
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Cell Structure & Organelles in detailed.
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
master seminar digital applications in india
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Business Ethics Teaching Materials for college
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Insiders guide to clinical Medicine.pdf
O7-L3 Supply Chain Operations - ICLT Program
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
BƀI Tįŗ¬P Bį»” TRỢ 4 KỸ NĂNG TIįŗ¾NG ANH 9 GLOBAL SUCCESS - Cįŗ¢ NĂM - BƁM SƁT FORM Đ...
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Week 4 Term 3 Study Techniques revisited.pptx
Ā 
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Anesthesia in Laparoscopic Surgery in India
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Classroom Observation Tools for Teachers
PPH.pptx obstetrics and gynecology in nursing
Cell Structure & Organelles in detailed.
Microbial disease of the cardiovascular and lymphatic systems
master seminar digital applications in india
human mycosis Human fungal infections are called human mycosis..pptx
Business Ethics Teaching Materials for college
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Insiders guide to clinical Medicine.pdf

Unit 5 File handling in C programming.pdf

  • 2. File: • A file a collection of data stored in one unit, identified by filename. • The primary purpose of a file is to keep record of data and record is the group of related fields. • Each file ends with an end of file(EOF) at a specified byte number, recorded in FILE structure. • A file must first be opened properly before it can be accessed for reading or writing. When a file is opened an object(buffer) is created and a file is associated with the buffer. • In general, file is a collection of related records such as student’s name, date of birth, address, marks, phone number etc. • A file is nothing but a source of storing information permanently in the form of a sequence of bytes on a disk. 2
  • 3. Buffer: When the computer reads, the data move from the external device to memory and when it writes, the data move from memory to the external device. This data movement often uses a special work area known as buffer. •A buffer is a temporary storage area that holds data while they are being transferred to or from memory. •The primary purpose of a buffer is to synchronize the physical devices with a program’s need. 3
  • 4. File Handling: •File handling is the process of storing data in the form of input or output produced by running C programs in data file for future reference and analysis. And, we can extract/fetch data from a file to work with it in the program. •File handling provides a mechanism to store the output of a program in a file and to perform various operations on it. •File handling concept provides various operations like creating a file, opening a file, reading a file or manipulating data inside a file etc. 4
  • 5. Why file handling? •The data stored in the various of a program will be lost once the program is terminated because they are stored in the Random Access Memory(RAM) which is volatile memory. •So, if we want store that data(input/output) used in the program permanently inside the secondary storage device so that, we can access these data from there whenever it is needed file handling concept is important. 5
  • 6. Block diagram of file accessing using a various function written to a file and read from a file using various functions: 6
  • 7. Types of file: There are two types of file namely: 1. Text file 2. Binary file 3. Text file: • These are the simplest files a user can create when dealing with file handling in C. • It is created with a .txt extension using any simple text editor. • A text file stores information in the form of ASCII characters internally, but when you open the text file, you would find the content of the text readable to humans. • Text file consume large storage space. • Example: new.txt, file.c etc. 7
  • 8. 2. Binary file: •A binary file stores information in the form of the binary number system (0’s and 1’s) and hence occupies less storage space. •In simple words, it stores information in the same way as the information is held in computer memory. Therefore, it proves to be much easier to access. •Example: file.dat, photo.jpg, one.png, song.mp3, file.exe etc. 8
  • 9. Difference between Text File and Binary File :- Text File Binary File 1. Output Formatted Text. 1. Output in 0 and 1 binary format. 2. EOF(End of File), n(New Line) are used. 2. Binary mode not use such character. 3. fgetc ( ), fputc ( ), fprintf ( ), fscanf ( ), fgets ( ), fputs ( ) are used. 3. fread ( ) and fwrite ( ) functions are commonly used. 4. Numbers are stored as string. 4. Numbers are stored as int, float etc. 5. Takes more access time. 5. Takes less access time. 6. It occupies more memory than binary file. 6. It occupies less memory than text file. 9
  • 10. Operations on File: •Creating of a new File •Opening an existing File •Reading from a File •Write to a File •Moving to a specific location in a file •Closing a File 10
  • 11. File Operation Modes: The different file mode that can be used in opening file are: Mode Description ā€œwā€ (write) If the file doesn't exist then this mode creates a new file for writing, and if the file already exists then the previous data is erased and the new data entered is written to the file. ā€œrā€ (read) This mode is used for opening an existing file for reading purpose only. The file to be opened must exist and the previous data of the file is not erased. ā€œaā€ (append) If the file doesn't exist then this mode creates a new file and if the file already exists then the new data entered is appended at the end of existing data. In this mode, the data existing in the file is not erased as in ā€œwā€ mode. ā€œw+ā€ (write + read) This mode is same as ā€œwā€ mode but in this mode we can also read and modify the data. If the file doesn't exist then a new file is created and if the file exists then previous data is erased. ā€œr+ā€ (read + write) This mode is same as ā€œrā€ mode but in this mode we can also write and modify existing data. The file to be opened must exist and the previous data of file is not erased. Since we can add new data and modify existing data so this mode is also called update mode. ā€œa+ā€ (append + read) This mode is same as the ā€œaā€ mode but in this mode we can also read the data stored in the file. If the file doesn't exist, a new file is created and if the file already exists then new data is appended at the end of existing data. We cannot modify existing data in this mode. 11
  • 12. File Operation Modes: Continue… Mode Description ā€œwbā€ Binary file opened in write mode. ā€œabā€ Binary file opened in append mode. ā€œrbā€ Binary file opened in read mode. ā€œwb+ā€ Create a binary file for read/write. ā€œrb+ā€ Open a binary file for read/write. ā€œab+ā€ Append a binary file for read/write. 12
  • 13. Text mode • In text mode every digit or text are stored as a character and while reading the content back, the conversion is required from character to appropriate format and takes lots of space. • Character I/O, string I/O, and formatted I/O use text mode. • If 3.14159 is stored in character mode file size would be 8 bytes (counts each character including decimal and EOF). Binary mode • In binary mode every digit or text is stored in binary format and while reading the content no conversion is necessary and takes little space. • fread ( ) and fwrite ( ) are used in binary mode. • If 3.14159 is stored in character mode file size would be 4 bytes. 13
  • 14. Opening a file: • A file must be opened before any I/O operations performed on that file. The process of establishing a connection between the program and file is called opening the file. • A structure named FILE is defined in the file <stdio.h> that contains all information about the file like name, status, buffer size, current position, end of file status etc. • All these details are hidden from the programming and the operating system takes care of all these things. • A file pointer is a pointer to a structure of type FILE. • Whenever a file is opened, a structure of type FILE is associated with it and a file pointer that points to this structure identifies this file. • Example: FILE *fp; • The function fopen ( ) is used to open a file. • Syntax: fp=fopen(ā€œpath:filename.extā€, ā€œfile_operation_modeā€); 14
  • 15. Closing a file: • The file that was opened using fopen ( ) function must be closed when no more operations are to be performed on it. • After closing the file, connection between file and program is broken. • On closing the file, all the buffers associated with it are flushed i.e all the data that is in the buffer is written to the file. • The buffers allocated by the system for the files are freed after the file is closed, so that these buffers can be available for other files. • Although all the files are closed automatically when the program terminates, but sometimes it may be necessary to close the file by using fclose( ) function. • Syntax: fclose(name_of_file_pointer); • Example: fclose(fp); 15
  • 16. End of file (EOF): •The file reading function need to know the end of file so that they can stop reading. •When the end of file is reached, the operating system sends an end-of-file signal to the program. •When the program receives this signal, the file reading function returns EOF, which is a constant defined in the file <stdio.h> and its value is -1. •This is only applicable to text mode file only. 16
  • 17. File Processing Techniques: The approach to read or to write the content from/to the file is know as file processing. There are basically two types of file processing techniques namely: 1. Sequential file processing: In this type of files data is kept in sequential order if we want to read the last record of the file, we need to read all records before that record so it takes more time. 2. Random file processing: In this type of files data can be read and modified randomly .If we want to read the last record we can read it directly. It takes less time when compared to sequential file. 17
  • 18. Input/output Functions: The functions used for file input/output are 1. Character I/O fputc( ) : •This function writes a character to the specified file at the current file position and then increments the file position pointer. •Syntax: fputc(character,file_pointer); fgetc( ) : •This function reads a single character from a given file and increments the file pointer. •Syntax: fgetc(file_pointer); 18
  • 19. 2. Integer I/O: putw( ): •This function writes an integer value to the file pointed to by file pointer. •Syntax: putw(Integer,file_pointer); getw( ): •This function returns the integer value from the file associated with file pointer. •Syntax: getw(file_pointer); 19
  • 20. 3. String I/O: fputs(): •This function writes the null terminated string pointed by given character pointer to a file. •Syntax: fputs(string,file_pointer); fgets(): •This function is used to read characters from a file and these characters are stored in the string pointed by a character pointer. •Syntax: fgets(string,length_of_string,file_pointer); 20
  • 21. Formatted Input/output Functions: fprintf( ) -This function is same as the printf( ) function but it writes formatted data into the file instead of the standard output(screen). -This function has same parameters as in printf( ) but it has one additional parameter which is a pointer of FILE type, that points to the file to which the output is to be written. Syntax: fprintf( fp, ā€œcontrol_stringā€,list of variables); 21
  • 22. Example: Program used to write name, roll no and marks of student using fprintf function. int main() { FILE *fp; char name[20]; int rollno; float marks; fp=fopen("std.txt","w"); if(fp==NULL) { printf("File can not open."); } printf("Enter Name: "); gets(name); printf("Enter roll.no: "); scanf("%d",&rollno); printf("Enter marks: "); scanf("%f",&marks); printf("Now writing data into file....."); fprintf(fp,ā€œName=%snRoll.no=%dnMarks=%.1f", name,rollno,marks); fclose(fp); getch(); return 0; } 22
  • 23. fscanf( ) - This function is similar to the scanf( ) function but it reads data from file instead of standard input, so it has one more parameter which is a pointer of FILE type and it points to the file from which data will be read. Syntax: fscanf( fp, ā€œcontrol_stringā€, &list_of_variables); 23
  • 24. Example: Program to read data from a file using fscanf function. int main() { FILE *fp; char name[20]; int rollno; float marks; fp=fopen("std.txt","r"); if(fp==NULL) { printf("File can not open."); } fscanf(fp,"%s %d %f",name,&rollno,&marks); printf("%s %d %.1f",name,rollno,marks); fclose(fp); } 24
  • 25. Random access in a file: •Random access means you can move to any part of a file and read or write data from it without having to read through the entire file. •In this technique the content are stored sequentially and read back the content from any position of the file. And it can be performed using some function like 1. fseek( ) 2. rewind( ) 3. ftell( ) 25
  • 26. 1. fseek ( ): • This function is used to move file position to a desired location within a file. • Syntax: int fseek(fp, long int offset, int position); - where, fp is a file pointer of type FILE which identifies the file. - The offset specifies the number of positions(bytes) to be moved from the location specified by position. - The offset may be positive means move forward or negative means move backwards. - The value of the positon may be 0 or 1 or 2. Value Constant Meaning 0 SEEK_SET Beginning of the file 1 SEEK_CUR Current position 2 SEEK_END End of the file 26
  • 27. Continue… Function Meaning fseek(fp,n,SEEK_CUR) Set file position ahead from the current position by n bytes. fseek(fp,-n,SEEK_CUR) Set file position back from the current position by n bytes. fseek(fp,0,SEEK_END) Set file position to the end of the file. fseek(fp,0,SEEK_SET) Set file position to the beginning of the file. 27
  • 28. //Example of fseek( ): #include<stdio.h> #include<conio.h> void main() { FILE *fp; char str[30]; fp=fopen("abc.txt","r"); if(fp==NULL) { printf("File can not open."); } else { fgets(str,29,fp); printf("%sn",str); fseek(fp,3,SEEK_SET); fgets(str,29,fp); printf("%sn",str); fseek(fp,-3,SEEK_CUR); fgets(str,29,fp); printf("%sn",str); fseek(fp,-4,SEEK_END); fgets(str,29,fp); printf("%s",str); } getch(); } 28
  • 29. 2. ftell ( ): •This function is used to get the current position of the file pointer. •Syntax: int ftell(FILE *fp); - This function will return the relative offset(bytes) of the current position and fp is the file pointer. - This function will tell us that how many bytes already been read or written. 29
  • 30. //Example of ftell( ): #include<stdio.h> #include<conio.h> void main() { FILE *fp; char str[30]; fp=fopen("abc.txt","r"); if(fp==NULL) { printf("File can not open."); } else { fseek(fp,-3,SEEK_END); int n=ftell(fp); printf("Current position of the file pointer is %d",n); } getch(); } 30
  • 31. 3. rewind ( ): •This function is used to set the file pointer at the beginning of the file. •Syntax: void rewind(FILE *fp); - Where, fp is the file pointer which identify the file. 31
  • 32. Example of rewind( ): #include<stdio.h> #include<conio.h> void main() { FILE *fp; char str[30]; fp=fopen("abc.txt","r"); if(fp==NULL) { printf("File can not open."); } else { fseek(fp,-3,SEEK_END); rewind(fp); int n=ftell(fp); printf("Current position of the file pointer is %d",n); } getch(); } 32
  • 33. Deleting a File: - We use remove () to delete a file. Syntax: remove( ā€œfile_nameā€); Example: int main() { remove("std.txt"); printf("Your file is successfully deleted."); getch(); return 0; } 33
  • 34. Renaming a File: -We use rename ( ) to rename a file. Syntax: rename(ā€œexisting_file_nameā€, ā€œnew_file_nameā€); Example: int main() { rename("std.txt","std1.txt"); printf("Your file is renamed successfully."); getch(); return 0; } 34
  • 35. Error Handling in Files: • It is possible that an error may occur during I/O operations on a file. • It is quite common that errors may occur while reading data from a file in C or writing data to a file. For example, an error may arise due to the following: - A file is opened with an Invalid name. - When the data accessed is beyond the EOF character from the file. - When a file is opened for one purpose but trying to perform different operations. - When a hidden file is trying to open then we can also get an error. - If the file is write protected then also we can get an error. - To handle these type of error, C provides error handling functions and these are: 1. feof ( ) 2. ferror ( ) 35
  • 36. 1. feof ( ): • This function is used to detect the end of file (eof) character in the file. • This function returns non-zero if file pointer is on EOF otherwise it returns 0. • Syntax: feof(file pointer variable); • Example: feof(fp); 2. ferror ( ): • This function is used to detect the errors while reading from the file or writing into the file. • It returns a non-zero value when an error is occurred while performing read and write operations otherwise it returns zero. • Syntax: ferror(file pointer variable); • Example: ferror(fp); 36
  • 37. fgetc() or getc(), fgets() and fscanf(): These functions are input functions which read formatted or unformatted data from the file. fputc() or putc(), fputs() and fprintf(): These functions are output functions which write formatted or unformatted data to the file. These functions are not suitable for reading or writing large amount of data ( block of data) to/from a file. So we use two additional functions: 1. fwrite() 2. fread() 37
  • 38. 1. fwrite ( ): - Used to write block or record (fixed length group of data) of data to a file. A record may be an array or a structure. Syntax: fwrite( ptr, int size, int n, FILE *fp ); Where, ptr : ptr is the reference (address) of an array or a structure stored in memory. size : size is the total number of bytes to be written. n : n is number of times a record will be written. fp : fp is a file pointer where the records will be written in binary mode. 38
  • 39. Example of fwrite (): #include<stdio.h> #include<conio.h> struct Student { int roll; char name[25]; float marks; }; int main() { FILE *fp; char ch; struct Student S; fp = fopen("Student.txt","w"); if(fp == NULL) { printf("nFile Can't open."); } do { printf("Enter Roll : "); scanf("%d",&S.roll); printf("Enter Name : "); scanf("%s",S.name); printf("Enter Marks : "); scanf("%f",&S.marks); fwrite(&S,sizeof(S),1,fp); printf("nDo you want to add another data (y/n):n "); ch = getche(); }while(ch=='y' || ch=='Y'); printf("nData written successfully..."); fclose(fp); getch(); return 0; } 39
  • 40. 2. fread ( ): -Used to read block or record (fixed length group of data) of data from a file. Syntax: fread( ptr, int size, int n, FILE *fp ); Where, ptr : ptr is the reference of an array or a structure where data will be stored after reading. size : size is the total number of bytes to be read from file. n : is number of times a record will be read. fp: fp is a file pointer from where the records will be read. 40
  • 41. Example of fread(): #include<stdio.h> #include<conio.h> struct Student { char name[25]; int roll; float marks; }; int main() { FILE *fp; struct Student S; fp = fopen("Student.txt","r"); if(fp == NULL) { printf("File Can't open."); } fread(&S,sizeof(S),1,fp); printf("Name=%sn",S.name); printf("Roll NO=%dn",S.roll); printf("Marks=%.1fn",S.marks); fclose(fp); getch(); return 0; } 41
  • 42. Simple Example of append mode: #include<stdio.h> #include<conio.h> #include<string.h> int main() { FILE *fp; int i; char ch[50]={"Kathmandu BernHardt"}; fp=fopen("new.txt","a"); if(fp==NULL) { printf("File can not open."); } for(i=0;i<strlen(ch);i++) { fputc(ch[i],fp); } fclose(fp); getch(); return 0; } 42
  • 43. Q. Given a text file, create another text file deleting the following words ā€œthreeā€, ā€œbadā€ and ā€œtimeā€. #include<stdio.h> #include<conio.h> #include<string.h> int main() { FILE *fp, *fpp; Char C[10]; fp=fopen(ā€œfile.txtā€, ā€œrā€); if(fp==NULL) { printf(ā€œFile Can not open.ā€); } fpp=fopen(ā€œtext.txtā€, ā€œwā€); if(fpp==NULL) { printf(ā€œFile can not open.ā€); } While(fscanf(fp, ā€œ%sā€, &c)!=EOF) { if(((strcmp(c,ā€threeā€)!=0 && (strcmp(c,ā€badā€)!=0 && (strcmp(c, ā€œtimeā€)!=0)) { fprintf(fpp, ā€œ%sā€,c); } fclose(fp); fclose(fpp); getch(); return 0; } 43