0% found this document useful (0 votes)
2 views

FileHandlingNotes

Uploaded by

sammaparween1992
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

FileHandlingNotes

Uploaded by

sammaparween1992
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

File Handling

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

1. Opening 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.

Closing a data file

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.

Prepared by:Ravi Kr Singh 1


i. Writing to a file

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.

Example: program to demonstrate writing one character at a time to a file.

#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);

Where ch is a character variable and fptr is a file pointer.

Example: program to demonstrate reading of one one character at a time from a file and display it on screen.

Prepared by:Ravi Kr Singh 2


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
FILE *fptr;
char ch,filename[20];
clrscr();
printf("Enter file name:");
scanf("%s",filename);
fptr=fopen(filename,"r");
if(fptr==NULL)
{
printf("Cannot open file");
getch();
exit(0);
}
fflush(stdin);
while((ch=fgetc(fptr))!=EOF)
{
putchar(ch);
}
getch();

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

The syntax of the function that writes a string of characters at a time is

fputs(str,fptr);
Where str is a array of characters or a string constants and fptr is file pointer.

Example: program to demonstrate writing of string to a file.

#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);
}

fputs("Fputs puts the entire string to a file",fptr);


fclose(fptr);
getch();
}

ii. Reading from a file

The syntax of a function that reads from a file is

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

Prepared by:Ravi Kr Singh 4


These functions are used to read numbers, characters or strings form the file or write them to file in format as
our requirement.

i. Writing to a file

The syntax of the function that writes formatted data to a file is

fprintf(fptr,”format-string”,list_of_variables);

ii. Reading from a file

The syntax of the function that reads formatted data from a file is

fscanf(fptr,”format-string”,&list_variables);

Example: Program to demonstrate writing of formatted data to a file

#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();
}

Example: Program to demonstrate reading of formatted data from a file.

#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( );
}

Example : Write and read example using fprintf() and fscanf()

#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;
}

Text mode vs Binary mode

Depending on the way the file is opened for processing, a file can be classified as a text file or binary file.

Prepared by:Ravi Kr Singh 7


The mode of opening a particular file determines how various details of the file are handled. For example: how
newline character is stored and how EOF is indicated.
The number in the text mode are stored as string of characters whereas in binary format they are stored in the
same way as they are stored in the computer memory. For example, the number1234 is to be stored in memory,
when transferred to the disk using fprintf(), it would occupy four bytes, one byte per character where as in
binary mode it would only occupy 2 bytes.
Hence if a large amount of numerical data is to be stored in a disk file, it is efficient to open file in binary mode
by using the function fread() and fwrite().
Mode Purpose
rb Reading only from binary file
wb Writing only to binary file. If file does not exist, it creates file.
ab Appending new content at the end of binary file
r+b Reading and writing new contents to binary file. It cannot create file.
w+b Writing new content and reading existing content to binary file.
a+b Reading existing content and appending new content to binary file.
Record Input/Output

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

The syntax of the function that writes block of data at a time is


fwrite(ptr,m,n,fptr);

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.

ii. Reading from a file

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.

Example: program to demonstrate writing of an entire array to a file.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char filename[20];
int a[10],i;

Prepared by:Ravi Kr Singh 8


printf("Enter the name of the file:");
scanf("%s",&filename);
fptr=fopen(filename,"wb");
if(fptr==NULL)
{
printf("Cannot create file");
getch();
exit(0);
}
for(i=0;i<10;i++)
{
a[i]=i+1;
}
fwrite(&a,sizeof(a),1,fptr);
fclose(fptr);
getch();

Example: program to demonstrate reading of an entire array from a file.

#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]);
}

Prepared by:Ravi Kr Singh 9


Example: program to demonstrate writing an entire structure to a file.

#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();

Example: program to demonstrate writing array of structure to a file.

#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();

Example: program to demonstrate reading array of structure from a file.

#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);

Prepared by:Ravi Kr Singh 13


}

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.

Different functions used in random access are given below:

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.

Mode Offset is measured form


0(SEEK_SET) Beginning of the file
1(SEEK_CUR) Current position of the file
2(SEEK_END) End of the file

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);

iii. ftell( ) function

Example: Program to demonstrate the use of ftell function


In some situation, it may be required to find the current location of the file pointer within the file. The ftell( )
function lets us know the current position of the file pointer. The syntax of ftell( ) function is

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();
}

Some other operations on data file

1. Renaming the file: The function rename() is used to rename file.


Syntax: rename(“Old_file_name”,”new_file_name”);

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”);

Prepared by:Ravi Kr Singh 16

You might also like