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

M5 Filehandling

The document discusses files and streams in C++. It describes how programs can read and write to files using file streams and input/output operations. It covers opening, closing, reading and writing to files as well as manipulating file pointers.

Uploaded by

Malavika Vipin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

M5 Filehandling

The document discusses files and streams in C++. It describes how programs can read and write to files using file streams and input/output operations. It covers opening, closing, reading and writing to files as well as manipulating file pointers.

Uploaded by

Malavika Vipin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Files and Streams

Files
• Many real-life problems handle large volumes
of data. The data is stored in the devices using the
concept of files.
• A file is a collection of related data stored in
a particular area on the disk.
• A computer file is a computer resource for
recording data discretely in a computer storage
device.
• Programs are designed to perform read and
write operations on these files.
Console-Program-File interaction
Program File Communication

• In C++ file streams are used as an interface


between the program and the files.
• The stream that supplies data to the program is
known as input stream and the one that receives
data from the program is known as output stream.
• Input stream => reads data
• Output stream => writes data
File input and Output Streams
Classes for File Stream Operations

ios
file m
a
tre

istream streambuf ostream


io s

iostream

ifstream fstream ofstream filebuf


fil am
re
e
fs t

fstream base
Opening and Closing a File
• To open a file, a file stream is created and then it is
linked to the filename.
• A file can be opened in two ways:

▫ Using the constructor function of the class.


▫ Using the member function open() of the class.
• A file is closed by using the function close().
• eg: outfile.close();
Opening File using Constructor
• Filename is used to initialize the file stream object.
• Create a file stream object to manage the stream.
▫ ofstream is used to create output stream.
▫ ifstream is used to create input stream.
• Initialize the file object with the desired filename.
• Eg:

ofstream outfile (“results”); // output only


ifstream infile (“data”); // input only
Opening File using Constructor
ifstream inf(“Item”);
#include<iostream.h>
#include<fstream.h> inf >> name;
int main() inf >> cost;
{
ofstream outf(“Item”); cout <<
cout<<“Enter item “Item
name:”; char name[30]; name :” <<
cin >> name; name;
outf<<name; cout <<
cout<<“Enter item “Item cost :”
cost:”; float cost;
cin >> cost; << cost ;
outf << cost;
inf.close();
outf.close(); return 0;
}

Output:
Enter item
Opening Files Using open()
• The function open() can be used to
open multiple files that use the same stream object.
• Syntax:
file-stream-class stream-
object; stream-
object.open(“filename”);
• A stream object can be connected to only one file at a
time.
Opening Files Using open()
const int N=80;
char line[N];
#include<iostream.h> ifstream fin;
#include<fstream.h> fin.open(“Country”);
cout<<“Contents of
int main()
country file” ;
{
ofstream fout; while(fin)
fout.open(“Country”); {
fin.getline(lin
fout<<“United state of e, N);
America\n”; cout<<line;
fout<<“United }
Kingdom\n”; fin.close();
fin.open(“Capi
fout.close(); tal”);
cout<<“Conte
fout.open(“Capital”); nts of capital
file”;
fout<<“Washington\n” while(fin)
fout<<“London”; {
fin.ge
fout.close();
tline(l
Detecting End-of File
• Detection of the end-of-file condition is necessary for preventing any
further attempt to read data from the file.

while(fin)

• An ifstream object return a value zero if any error occurs in the file
operation including the end-of-file condition.

if(fin1.eof() != 0 ) { exit(1); }

• The eof() of ios class returns a non zero value if the end-of-file
condition is encountered and zero otherwise.
Opening two files simultaneously

• When two or more files are used simultaneously


ie: when we want to merge two files into a single
file.
• In such case we create two separate input
streams for handling the two input files and one
output stream for handling the output file.
Opening two files simultaneously
#include<iostream.h>
#include<fstream.h> fin1.getline(line,size);
#include<stdlib.h> cout << “Capital of “ << line;
int main()
{ if ( fin2.eof() ! = 0 )
const int size = 80; char {
line[size]; cout << “ \n Exit from capital \n“ ;
ifstream fin1, fin2; exit(1);
fin1.open(“country”); }
fin2.open(“capital”); fin2.getline(line,size);
for(int i = 1; i <= 10; i++ ) cout << line << “\n”;
{ }
if ( fin1.eof() ! = 0) return 0;
{
}
cout << “\n Exit from
country \n ” ;
exit(1);
File Modes
• File mode specifies the purpose for which the file is
opened.
• File mode parameters:

▫ ios::app //Append to end-of-file


▫ ios::ate //go to end-of-file on opening
▫ ios::binary //Binary file
▫ ios::in //open file for reading only
▫ ios::nocreate //open fails if the file does not exists.
▫ ios::noreplace //open fails if the file already exists.
▫ ios::out //open file for writing only
▫ ios::trunc //delete the contents of file if it exists
File Pointers
• Each file has two associated pointers:
▫ get pointer or input pointer: used for reading the
contents
of the file.
▫ put pointer or output pointer: used for writing to a given
file location.
• Default actions associated with both the pointers.
▫ When a file is opened in read mode the input pointer is set
at the beginning.
▫ When a file is opened in write mode the existing
contents
Default Actions
Manipulation of File Pointers
• The user can control the movement of the pointers as per
his need by using the following functions:
▫ seekg() : moves get pointer to a specified location.
▫ seekp(): moves put pointer to a specified location.
▫ tellg() : gives the current position of the get pointer.
▫ tellp() : gives the current position of the put pointer.
File Pointers
• File pointers seekg() and seekp() can also be used with
two arguments:
▫ seekg(offset, refposition);
▫ seekp(offset, refposition);
• The parameter offset represents the number of bytes
the file pointer is to be moved from the location
specified by the parameter refposition.
• The refposition can take one of the following three
constants defined in the ios class:
▫ ios::beg // start of the file
▫ ios::cur // current position of the pointer
▫ ios::end //end of the file
File Pointers (Pointer Offset calls)
▫ fout.seekg(0,ios::beg); // go to start
▫ fout.seekg(0,ios::cur); // stay at the current position
▫ fout.seekg(0,ios::end); // go to end of the file
▫ fout.seekg(m,ios::beg); // move to (m+1)th byte in the file
▫ fout.seekg(m,ios::cur); //go forward by m byte from the
current position

▫ fout.seekg(-m,ios::cur); // go backward by m bytes from


the current position

▫ fout.seekg(-m,ios::end); //go backward by m bytes from


the end
Sequential Input & Output Operations

• The file stream class support a number of


member functions for performing the input and
output operations on files.
▫ put() and get() : used for handling a single
character.
▫ read() and write() : used for handling large blocks
of binary data.
put() & get() functions

• Function put() writes a single character to


the associated stream.
• Function get() reads a single character from the
associated stream.
put() & get() functions
#include<iostream> char ch;
#include<fstream> while(file)
#include<cstring> {
using namespace std;
file.get(ch);
int main()
{ cout << ch;
char string[80]; }
cout << “Enter a
string :\n ”; return 0;
cin >> string; }
int len = strlen(string);
fstream file;
file.open(“Text”, ios::in |
ios::out);

for(int i = 0; i < len ;i++)


file.put(string[i]);
file.seekg(0);
Reading & Writing a class object

• C cannot handle user defined data types such


as class objects.
• C++ provides read() and write() functions to
read and write the objects directly.
• The length of the object is obtained using
thesizeof operator.
• This length represents the sum total of lengths of all
data members of the object.
Reading & Writing a class object

• Syntax:
▫ infile.read ((char *) & V, sizeof (V));
▫ outfile.write ((char *) & V, sizeof (V));
• The first argument is the address of the variable V.
• The second is the length of that variable in bytes.
• The address of the variable must type cast to char *
(ie: pointer to character type).
Example
#include<iostream> void inventory :: readdata(void)
{
#include<fstream> cout<<“Enter name:”;
using namespace std; cin>> name;
cout<<“Enter code:”;
class inventory cin>>code;
{ cout<<“Enter cost:”;
cin>> cost;
char name[10]; }
int code; void inventory :: writedata(void)
{
float cost;
cout<<name;
public:
cout<<code;
void readdata(void); cout<<cost;
void writedata(void); }
};
int main()
{
inventory item[3];
fstream file;
file.open(“Stock.dat”, ios::in | ios::out);
cout<<“Enter the details for three items:”;
for(int i=0; i<3;i++)
{
item[i].readdata();
file.write((char *) & item[i], sizeof(item[i]));
}
file.seekg(0);
for(i=0;i<3;i++)
{
file.read((char *) & item[i], sizeof(item[i]));
item[i].writedata();
}
file.close();
return 0;
}
Updating a File: Random Access

• Updating is a routine task in the maintenance of any data file.


• The updating would include one or more of the following tasks:

■ ▫ Displaying the contents of a file.


■ ▫ Modifying an existing item.
■ ▫ Adding a new item.
■ ▫ Deleting an existing item.
Updating a File: Random Access

• The size of each object can be obtained using the statement:


■ Int obj_len = sizeof(object);
• The location of a desired object (say m) is obtained as:
■ int location = m * obj_len;
• The total number of objects in a file
can be obtained by using object length as:
■ int n = file_size / obj_len;
Error Handling During File Operations

• Following conditions may arise while dealing with


files:
▫ A file which we are attempting to open for
reading does
not exists.
▫ The file name used for a new file may already
exists.
▫ We may attempt an invalid operation such as reading
past the end-of-file.
▫ There may not be any space in the disk for storing more
data.
▫ We may use invalid file name.
▫ We may attempt to perform an operation when the file is
not opened for that purpose.
Error Handling During File Operations
• The ios class supports several member functions that can
be used to read the status recorded in a file stream.

Function Return value and meaning


eof( ) Returns true (non zero value) if end-of-file is encountered
while reading otherwise returns false (zero).

fail( ) Returns true when an input or output operation has failed.


bad ( ) Returns true if an invalid operation is attempted or any
unrecoverable error has occurred. However, if it is false, it
may be possible to recover from any other error reported, and
continue operation.

good ( ) Returns true if no error has occurred. When is returns false,


no further operations can be carried out.
Error Handling During File Operations
......
......
ifstream infile;
infile.open(“ABC”);
while ( !infile.fail( ))
{
.........
( proces
s the
file )
.........
}
if (infile.eof( ) )
{
.........

(termin
ate
progra
m
normall
y)
} infile.clear ( ); // clear error state
else
.........
if(infile.
} bad ( ))
{ ..........
.......... ..........

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy