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

C-7 File Handling

1. The document discusses data files and file handling in C++. It describes different types of files like text files and binary files. It also explains concepts like file streams, file pointers, different file access modes, and functions for reading from and writing to files. 2. Examples are provided to demonstrate writing text to a file, reading from a file, and copying contents from one file to another. A program is also described to write student object data to a file and then read it back. 3. Functions are defined to read and write student object data from a file using member functions. Appropriate file handling functions are used to read data, display it, and add a new record to the file.

Uploaded by

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

C-7 File Handling

1. The document discusses data files and file handling in C++. It describes different types of files like text files and binary files. It also explains concepts like file streams, file pointers, different file access modes, and functions for reading from and writing to files. 2. Examples are provided to demonstrate writing text to a file, reading from a file, and copying contents from one file to another. A program is also described to write student object data to a file and then read it back. 3. Functions are defined to read and write student object data from a file using member functions. Appropriate file handling functions are used to read data, display it, and add a new record to the file.

Uploaded by

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

CHAPTER - 7

DATA FILE HANDLING


Data - It is collection of raw facts and figures, which have no meaning. But this data can be converted
into meaningful information.
File It is a Collection of data on a particular topic and stored on a storage device under a specific name.
File is an organized collection of data. It is a bunch of bytes stored on hard disk. Files are used to store
information so that it can be retrieved later on when required.
Types of Files Based on the storage the files are of two types:Text Files In these files data is stored in the form of ASCII codes. For each character ( numeric / digit
or alphabet) ASCII code is used. Text files can be manipulated using any text editor. They are easy to
understand. They occupy large space in the memory. When they are written on disk, they are first
converted into binary form and they stored. When they are read, they are converted from binary form to
ASCII form and then read on the output device. Thats why they are slow in nature. The EOF is marked
by a delimiter EOF.
Binary Files This file contains information in the machine language form. The EOF is not marked by
any delimiter. This file is not required to be translated as machine language is directly understood by the
computer.
Stream is a sequence of bytes. It is flow of data from source to destination.
File Handling Phenomenon Files are stored on the disk. When they are read from the disk into the main
memory, they are first copied into the input stream. Then from the input stream they are extracted into the
main memory. When they are written to the disk, from the main memory they are first copied into the
output stream. Then from the output stream they are written into the disk.
To perform input from a file we require ifstream class. To perform output into a file we require ofstream
class. The definition of both these classes is contained in the fstream class. When ever a file is to be
opened an object of either of these streams is created. These stream classes are inherited from istream,
ostream and iostream.
ifstream - object of ifstream is used to open the file. A file opened with ifstream object can only be read.
First the object of ifstream is created and then that object is used to open the file in read mode. The file
can be opened
IMP : To read a file it must have been created before reading it. To write a file it is not necessary that the
file is created before writing. It is automatically created when opened in writing mode.
Type of files based on their access Serial Access Files In a serial file records are arranged in the way they are inserted in a file.
There is no significance of primary key in a serial file. If a record is to be accessed the whole file from
top to bottom is to be searched.
Sequential Access files In these files records are arranged according to primary key. Records are
accessed in the order they are entered into the file.
Random Access Files In these files records are of fixed length and to access a particular record, all
the intervening records can be skipped and the record required can be accessed directly. There is no need

to visit all the records from top to bottom. Because of the fixed length records, computer is able to
calculated the exact address of the required record.
File Access Modes :
If a file is opened with fstream class object. Then mode in which the file is to be opened is given with the
file name. Following are the few modes
Mode
ios :: in
ios :: out
ios :: app
ios :: ate
ios :: binary
ios :: out | ios :: binary

Purpose
File is to be opened in input mode
File is to be opened in output mode from the beginning of the file, contents
of the file are overwritten
File is to be opened in append mode at end of the file, records appended at
the end of file
File is to be opened in append mode at end of the file, records can be
written anywhere in the file even in the middle or at the end of file
Opens the file in binary mode
Open the file in output mode and in binary mode

Some Important differences


Function
cin
gets()
get (char )
getline(line, 80,\0)
getch()
getche()
getchar()
read((char *) &object, sizeof(object))
Write((char *)&object, size of(object))
put(char )
puts()
Cout

Purpose
Gets input of stdin
Gets a string from stdin until terminated by newline
\n white spaces can be there in the string
Inputs the next character from input stream and
stores it in char argument
Reads input into array line from input stream max
char read is 80 or until \0 is encountered which
ever is earlier.
Input a single character from stdin but does not
echo it on the screen
Input a single character from stdin and echos it on
the screen
Gets a character from the stdin converts it into
integer and assigns it to an integer variable
eg
(c = getchar())
Reads input from the file into the addr of objects
and data read is of the size of the object
Write output into the file into the addr of objects
and data writen is of the size of the object
Puts one char on the output stream
Puts a string on the screen
Puts output on the screen

File Pointer It is a pointer to a particular byte in a file. The file pointer determines the position
in the while where the current operation is to occur.
Get Pointer is associated with the files opened in read mode.
seekg() and tellg() seekg = seek get
seekg() searches the location

tellg = tell get

Fileobject.seekg( no_of_bytes_to_skip, from_where_to_skip)


from_where_to_skip can be any of three values

ios :: beg
ios :: cur
ios :: end

from beginning of file


current position of file where opened
from end of file

tellg() returns the location of the pointer which can be stored in some variable. Eg
int location;
location = fileobject.tellg();
Put pointer is associated with the files opened in write mode.
seekp() and tellp()

seekp = seek put

tellp = tell put

seekp tells where the next output is to be placed in the file.


fileobject.seekp(location);
tellp() returns the current position of the put pointer (seekp)
int location = fileobject.tellp();

1.

Examples of a program to write text files and how to read that file

#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<fstream.h>
ofstream outputfile;
ifstream inputfile;
void main()
{
clrscr();
// char str[] = "I am mr lal. How are you?";
char strg[70];

//for outputfile

cout<<"\nEnter string to be written to file \n";


gets(strg);
outputfile.open("Plal.txt");
//outputfile<<"Hellow how are you";
//outputfile<<str;
outputfile<<strg;

//direct way for outputfile


//write in output file when initialized
//write file with contents written from kboard

outputfile.close();
char c;
ifstream inputfile("Plal.txt");
//opening file with constructor
if(inputfile)
//to check presence of file to be read
cout<<"\nThis file is in bin, see its contents\n";

//

while(!inputfile.eof())
while(inputfile.getline(strg,10))
{
//
inputfile.get(c);
//
cout<<c;
cout<<strg<<endl;
}

//way to read files with loop


//reading file using getline function
//in one line max char shown is 10
//show output using get()
//to show output when used getline()

inputfile.close();
getch();
}
2.

Write a Program to copy the contents of file plal.txt to file xyz.txt

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
fstream file1,file2,file3;
void main()
{
clrscr();
char strg[]="Hellow how are you? I am fine, thanks.";
file1.open("Plal.txt",ios::out);
file1<<strg;
file1.close();
char c;
// Copying contents of file Plal.txt to file xyz.txt
file3.open("xyz.txt",ios::out); //open file in which to copy contents
file2.open("Plal.txt",ios::in); //open file from which to copy contents
while(!file2.eof())
//loop to read contents of file to be copied
{
file2.get(c);
//reading characters from file
file3.put(c);
//writing charaters to file
}
file2.close();
file3.close();
cout<<"\n here is the contents of xyz.txt\n";
file3.open("xyz.txt",ios::in);
while(!file3.eof())
{
file3.get(c);
cout<<c;
}
file3.close();
getch();
}

3.

Program to write structures and objects into files and then reading them

to read/write structures and objects into files, first the data structure / object are copied into the memory
stream from there they are written/read into files.
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
class employee
{
private :
int empcode;
char empname[20],empdept[20],empaddr[20];
public :
void read_emp();
void show_emp();
};
void employee :: read_emp()
{
cout<<"\nEnter Emp Code = ";
cin>>empcode;
cout<<"\nEnter Emp Name = ";
gets(empname);
cout<<"\nEnter Emp Dept = ";
gets(empdept);
cout<<"\nEnter Emp Address = ";
gets(empaddr);
}
void employee :: show_emp()
{
cout<<empcode<<"\t"<<empname<<"\t"<<empdept<<"\t"<<empaddr;
}
employee emp;
fstream file1,file2,file3;
void main()
{
clrscr();
/*
//Code to writing into EMP.DAT after getting data from object emp.read_emp()
//comments can be put on reading block after writing data into emp
int nuofemp;
cout<<"\nEnter how many employees to = ";
cin>>nuofemp;
file1.open("EMP.DAT",ios::out);
int i;
for(i=0;i<nuofemp;i++)
{
emp.read_emp();
file1.write((char *)&emp,sizeof(employee));

}
file1.close();
*/
//code to read the contents of file EMP.DAT and then the contents are shown
//using the emp.show_emp() function
//comments can be put on writing block after writing data into emp
file2.open("EMP.DAT",ios::in);
while(file2)
{
file2.read((char *)&emp,sizeof(employee));
emp.show_emp();
cout<<"\n";
}
file2.close();
getch();
}
3.
Write a function program to read the data , show the data and any a record of an object stud from a
file. Use appropriate member functions.
#include<stdio.h>
#include<conio.h>
#include<fstream.h>
#include<process.h>
fstream file1,file2;
void write_stud(int );
void read_stud(int );
void find_stud(int );
class student
{
public :
int rollno;
char name[20];
public :
void get_data();
void show_data();
};
void student :: get_data()
{
cout<<"Enter Roll NO = ";
cin>>rollno;
cout<<"Enter Name = ";
cin>>name;
}
void student :: show_data()
{
cout<<rollno<<"\t"<<name<<endl;
}
student stud;
void main()
{
clrscr();

int xrollno,noofstud;
cout<<"Enter How many students = ";
cin>>noofstud;
write_stud(noofstud);
read_stud(noofstud);
cout<<"\nEnter Rol No of find : ";
cin>>xrollno;
find_stud(xrollno);
getch();
}
void write_stud(int noofstud)
{
int i;
file1.open("STUD.TXT",ios::out);
for(i = 0;i<noofstud;i++)
{
stud.get_data();
file1.write((char *)&stud,sizeof(stud));
}
file1.close();
}
void read_stud(int noofstud)
{
int i;
file2.open("STUD.TXT",ios::in);
for(i = 0;i<noofstud;i++)
{
file2.read((char *)&stud,sizeof(stud));
stud.show_data();
}
file2.close();
}
void find_stud(int recono)
{
int found = 0;
file1.open("STUD.TXT",ios::in|ios::binary);
while(file1)
{
file1.read((char *)&stud,sizeof(stud));
if(stud.rollno == recono)
{
stud.show_data();
found = 1;
exit(0);
}
}
if(found==0)
cout<<"\nREcord not found";
}

Q 4.

Write a program to enter books from an object of the class book and display them.

#include<iostream.h>
#include<stdio.h>
#include<fstream.h>
#include<conio.h>
class book
{
private :
int bookno;
char title[20];
public :
void enter_book()
{
cout<<"\nEnter Book No : ";
cin>>bookno;
cout<<"\nEnter tile of Book : ";
gets(title);
}
void show_book()
{
cout<<bookno<<" "<<title<<endl;
}
};
const int max =5;
book bk[max];
void main()
{
clrscr();
int i;
cout<<"Enter books \n";
for(i = 0;i<max;i++)
bk[i].enter_book();
for(i=0;i<max;i++)
bk[i].show_book();
getch();
}
Q5.

Same program using function calls.

#include<iostream.h>
#include<stdio.h>
#include<fstream.h>
#include<conio.h>
void books();
class book
{
private :
int bookno;
char title[20];
public :

void enter_book()
{
cout<<"\nEnter Book No : ";
cin>>bookno;
cout<<"\nEnter tile of Book : ";
gets(title);
}
void show_book()
{
cout<<bookno<<" "<<title<<endl;
}
};
book bk;
void main()
{
clrscr();
books();
getch();
}
void books()
{
bk.enter_book();
bk.show_book();
}

You might also like