FileHandlingNotes
FileHandlingNotes
File is a data structure where we can permanently store the data. In other words, file is the data structure which
helps us to store our data permanently on the secondary storage devices(ex: hardisk, flash disk, CD,DVD).
Steps that are involved in maintaining data files are:
1. Opening a file
2. Reading or writing from/on data file
3. Closing a data file
Before reading data from a data file or writing data to a file, we must open a file. Opening a file creates a
link between the program & operating system where we have to mention data file name and mode of
operation (reading or writing or appending). The link between program & operating system is controlled by
a structure called file. It is necessary to open a file before reading or writing to a file.
Syntax:
FILE *fptr;
fptr=fopen(“data_file_name”,”mode”);
For example:
fptr=fopen(“info.txt”,”w”);
Here fptr is a pointer variable which contains the address of the data structure file.
Mode defines purpose of opening the data file. The following are the modes in which data file can be
opened.
Mode Purpose
r Reading only from file
w Writing only to file. If file does not exist, it creates file.
a Appending new content at the end of file
r+ Reading and writing new contents. It cannot create file.
w+ Writing new content and reading existing content
a+ Reading existing content and appending new content.
After opening a data file, we can do reading/writing operations. After reading or writing operation we must
close a file. This is done with the function fclose.
syntax:
fclose(file_pointer);
EOF(End of file)
The EOF represents an integer and determines whether the file associated with a file handle has reached end of
file. This integer is set to the program by the operating system and is defined in header file stdio.h. While
creating a file, the operating system transmits the EOF signal when it finds last character.
Character Input/Output
Using character I/O data can be read or written one character at a time. This is analogous to the way functions
putchar( ) and getch( ) write data to screen and read data from the keyboard.
Once the program has established a line of communication with a particular file by opening it, then it can write
to the file. The syntax of function that writes one character at a time is
fputc(ch,fptr);
Where ch is a character variable and ptr is a file pointer.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char ch;
char filePath[50];
clrscr();
printf("Enter path of file:");
gets(filePath);
fptr=fopen(filePath,"w");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
printf("Enter any text.Hit enter key to stop writing:");
fflush(stdin);
while((ch=getchar())!='\n')
{
fputc(ch,fptr);
}
fclose(fptr);
getch();
getch();
}
ii. Reading from a file
If a program can write to a file, it should also be able to read from a file. The syntax of the function that reads
and returns one character at time is
ch=fgetc(fptr);
Example: program to demonstrate reading of one one character at a time from a file and display it on screen.
String Input/Output
Using string I/O, data can be read or written in the form of string of characters. Reading and writing strings of
characters is easier than reading individual characters. This is analogous to puts( ) and gets( ) function.
i. Writing to a file
fputs(str,fptr);
Where str is a array of characters or a string constants and fptr is file pointer.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
Prepared by:Ravi Kr Singh 3
char filename[20];
printf("Enter file name:");
scanf("%s",filename);
fptr=fopen(filename,"w");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
fgets(str,n,fptr);
where str is a string, n is the maximum length of the string and fptr is a file pointer.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char filename[20],s[100];
printf("Enter file name:");
scanf("%s",filename);
fptr=fopen(filename,"r");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
fgets(s,100,fptr);
fclose(fptr);
printf("The text from the file is:%s",s);
getch();
}
Formatted Input/Output
i. Writing to a file
fprintf(fptr,”format-string”,list_of_variables);
The syntax of the function that reads formatted data from a file is
fscanf(fptr,”format-string”,&list_variables);
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char filename[20],s,name[20];
int age;
float height;
printf("Enter file name:");
scanf("%s",filename);
fptr=fopen(filename,"w");
if(fptr==NULL)
{
printf("Cannot create file");
getch( );
exit(0);
}
do
{
printf("Enter name:");
scanf("%s",name);
printf("Enter age:");
scanf("%d",&age);
printf("Enter height:");
scanf("%f",&height);
fprintf(fptr,"%s\t%d\t%.2f\n",name,age,height);
printf("Do you want to enter more record:");
fflush(stdin);
scanf("%c",&s);
}while(s=='y' || s=='Y');
Prepared by:Ravi Kr Singh 5
fclose(fptr);
getch();
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char filename[20],name[20];
int age;
float height;
printf("Enter file name:");
scanf("%s",filename);
fptr=fopen(filename,"r");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
while(fscanf(fptr,"%s%d%f\n",name,&age,&height)!=EOF)
{
printf("Name=%s,Age=%d,Height=%.2f\n", name, age, height);
}
fclose(fptr);
getch( );
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
char choice,filepath[50];
char name[20];
float height;
int age;
printf("Enter file path along with filename.extension:");
scanf("%s",filepath);
Prepared by:Ravi Kr Singh 6
fptr=fopen(filepath,"w");
if(fptr==NULL)
{
printf("Cannot read file");
getch();
exit(0);
}
do{
printf("Enter age:");
scanf("%d",&age);
printf("Enter height:");
scanf("%f",&height);
printf("Enter name");
fflush(stdin);
gets(name);
fprintf(fptr,"%s\t%d\t%.2f\n",name,age,height);
printf("Do you want to enter more record:");
fflush(stdin);
choice=getchar();
}while(choice=='y' || choice=='Y');
fclose(fptr);
fptr=fopen(filepath,"r");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
return 1;
}
while(fscanf(fptr,"%s%d%f\n",name,&age,&height)!=EOF)
{
printf("Name=%s,Age=%d,Height=%.2f\n", name, age, height);
}
getch();
return 0;
}
Depending on the way the file is opened for processing, a file can be classified as a text file or binary file.
Record I/O sometimes also known as block I/O writes numbers to disk files in binary format, so that integers
are stored in two bytes, long integers are stored in 4 bytes and so on. i.e same format used to store data in
memory. Record I/O also permits reading and writing of data at once.Array, structures, array of structures e.t.c
can be read and written as a unit.
i. Writing a file
Where ptr is the address of an array or a structure to be written, m is the size of an array or a structure, n is the
number of such arrays or structures to be written and fptr is a file pointer of a file opened in binary mode for
writing. After writing the block, fwrite( ) function returns the number of data items actually written.
The syntax of the function that reads a block from a file is:
fread(ptr,m,n,fptr);
Where ptr is an address of an array of a structure where block will be stored after reading, m is the size of an
array or structure to be read, n is the number of such arrays or structures to be read and fptr is a file pointer of a
file opened in binary mode for reading.
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char filename[20];
int a[10],i;
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
int a[10],i;
char filename[10];
clrscr();
printf("Enter file name;");
scanf("%s",filename);
fptr=fopen(filename,"rb");
if(fptr==NULL)
{
printf("Cannot open file");
getch();
exit(0);
}
printf("Reading from file........");
fread(&a,sizeof(a),1,fptr);
for(i=0;i<10;i++)
{
printf("%d\t",a[i]);
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
struct student
{
char name[20];
int rollno;
float marks;
};
struct student s;
FILE *fptr;
int rno=1;
char filename[20];
clrscr();
printf("Enter filename:");
scanf("%s",filename);
fptr=fopen(filename,"wb");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
printf("Enter name,roll no. and marks:");
scanf("%s%d%f",s.name,&s.rollno,&s.marks);
fwrite(&s,sizeof(s),1,fptr);
fclose(fptr);
getch();
}
Example: program to demonstrate reading an entire structure from a file.
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
struct student
{
char name[20];
int rollno;
float marks;
};
struct student s;
FILE *fptr;
Prepared by:Ravi Kr Singh 10
int rno=1;
char filename[20];
clrscr();
printf("Enter filename:");
scanf("%s",filename);
fptr=fopen(filename,"rb");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
while(fread(&s,sizeof(s),1,fptr)>0)
{
printf("Record no.=%d\n",rno);
printf("Name=%s\n",s.name);
printf("roll no.=%d\n",s.rollno);
printf("Marks=%f\n",s.marks);
printf("\n\nPress any key to see the next record");
rno++;
getch();
}
fclose(fptr);
getch();
}
Alternative method:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
struct student
{
char name[20];
int rollno;
float marks;
};
struct student s[3];
FILE *fptr;
int i;
char filename[20];
clrscr();
printf("Enter filename:");
scanf("%s",filename);
fptr=fopen(filename,"rb");
if(fptr==NULL)
{
printf("Cannot create file");
Prepared by:Ravi Kr Singh 11
getch();
exit(0);
}
fread(&s,sizeof(s),3,fptr);
fclose(fptr);
for(i=0;i<3;i++)
{
printf("%s\t%d\t%.2f\n",s[i].name,s[i].rollno,s[i].marks);
}
getch();
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
struct student
{
char name[20];
int rollno;
float marks;
};
struct student s[3];
FILE *fptr;
int i;
char filename[20];
clrscr();
printf("Enter filename:");
scanf("%s",filename);
fptr=fopen(filename,"wb");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
for(i=0;i<3;i++)
{
printf("Enter information of %d students:\n\n",i+1);
printf("Name:");
scanf("%s",s[i].name);
Prepared by:Ravi Kr Singh 12
printf("Enter Roll no.:");
scanf("%d",&s[i].rollno);
printf("Enter marks:");
scanf("%f",&s[i].marks);
}
fwrite(&s,sizeof(s),3,fptr);
fclose(fptr);
getch();
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
struct student
{
char name[20];
int rollno;
float marks;
};
struct student s[3];
FILE *fptr;
int i;
char filename[20];
clrscr();
printf("Enter filename:");
scanf("%s",filename);
fptr=fopen(filename,"rb");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
fread(&s,sizeof(s),3,fptr);
for(i=0;i<3;i++)
{
printf("Record no.=%d\n",i+1);
printf("Name:%s\n",s[i].name);
printf("Roll no.:%d\n",s[i].rollno);
printf("Marks:%f\n",s[i].marks);
fclose(fptr);
getch();
Direct/Random Access
Reading and writing in all previous programs was sequential. That is while reading or writing, all items were
read from beginning of file in a sequence. We can access a particular data item placed in any location without
starting from the beginning. Such type of access to a data item is called direct random access.
File pointer: Before going ahead let us discuss about file pointer. A file pointer is a pointer to a particular byte
in a file. Every time, when we write to a file, the file pointer moves to the end of the data items written so that
writing can continue from that point. When a file is closed and subsequently opened for reading, the file pointer
is set to the beginning of the file so that we can read the file from the beginning. However, if the file is opened
in append mode, then the file pointer will be positioned at the end of the existing file, so that new data items can
be written from there onwards.
i. fseek( )
It sets the file pointer to a new position. This function is used to move the file pointer to different positions. The
syntax is
fseek(fptr,offset,mode)
where
• fptr is a file pointer.
• offset is a long integer that specifies the number of bytes by which the file pointer is moved.
• mode specifies from which position the offset is measure.
Example:
fseek(fptr,0,SEEK_SET) -> Moves the file pointer at the beginning of the file.
fseek(fptr,0,SEEK_END) -> Moves the file pointer at the end of the file.
fseek(fptr,10,SEEK_SET)-> Moves the file pointer 10 bytes right from the beginning of the file.
fseek(fptr,-2,SEEK_CUR)-> Moves the file pointer 2 bytes left from the current position of the file.
Prepared by:Ravi Kr Singh 14
fseek(fptr,2,SEEK_CUR)-> Moves the file pointer 2 bytes right from the current position of the file.
Example of fseek: Program to read and display the content of a file starting from 15th character.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char ch,filename[20];
clrscr();
printf("Enter path:");
scanf("%s",filename);
fptr=fopen(filename,"r");
if(fptr==NULL)
{
printf("Cannot read file");
getch();
exit(0);
}
fseek(fptr,15,SEEK_SET);
while((ch=fgetc(fptr))!=EOF)
{
putchar(ch);
}
getch();
}
ii. rewind( )
This function positions the file pointer in the beginning of the file. Its syntax is
rewind(fptr);
ftell(fptr);
Example: Program to demonstrate the use of ftell function
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char ch,filename[20];
long int pos=0;
clrscr();
printf("Enter path:");
scanf("%s",filename);
Prepared by:Ravi Kr Singh 15
fptr=fopen(filename,"r");
if(fptr==NULL)
{
printf("Cannot read file");
getch();
exit(0);
}
fseek(fptr,15,SEEK_SET);
pos=ftell(fptr);
printf("File pointer position is %ld",pos);
getch();
}
Example: rename(“student.dat”,”employee.dat”);
2. Removing / Deleting files: The function remove() is used to remove or delete the file.
Syntax: remove(“file_name”);
Example: remove(“student.dat”);