files in c++

34

Click here to load reader

Upload: selvin-josy-bai-somu

Post on 16-Apr-2017

2.241 views

Category:

Education


1 download

TRANSCRIPT

Page 1: Files in c++

FILES IN C++

Prepared by : SELVIN JOSY BAI.S

Page 2: Files in c++

Use of header file fstream.hTypes of stream objectsopen() and close() functionsFile mode constantsReading and writing characters from

/ to diskDetecting end of fileReading and writing objects from /

to diskFile pointers for Random AccessError handling functions

Page 3: Files in c++

Most computer programs work with files.

Word processors create document files.

Database programs create files of information.

Compilers read source files and generate executable files.

In C++, file input / output facilities are implemented through a component header file of C++ standard library. This header file is

fstream.h.

Page 4: Files in c++

File Stream Read data

A File stream act as an interface between the program and the files.

•The stream that supplies data to the program is known as input stream.

•The stream that receives data from the program is known as output stream.

Disk Files

Program

Data input

Write dataData output

Output stream

Input stream

Page 5: Files in c++

CLASSES FOR FILE STREAM OPERATIONSios

istream

streambuf

ostream

iostream

ifstream

fstream

ofstream

filebuf

fstreambase

…………………………………………………………………………………………………………………………………………….

iost

ream

fil

efs

trea

m

file

Page 6: Files in c++

Using fstream.hA stream is a sequence of bytes.

It is a general name given to a flow of data.Different streams are used to represent

different kinds of data flow.ifstream class represents input disk files.

ofstream class represents output disk files.fstream – for both input and output

Member functions of these classes are used to perform I/O operations.

Page 7: Files in c++

Different Classes and its functionsClass Functions

filebuf It sets the file buffers to read and write.Member functions : open(), close()

fstreambase This is the base class for fstream, ifstream and ofstream classes.Member functions : all input and output functions, open(), close()

ifstream It provides input operations for file.Member functions : get(), getline(), read(), seekg(), tellg()

ofstream It provides output operations for file.Member functions : put(), write(), seekp(), tellp()

fstream It is an input-output stream class

Page 8: Files in c++

Opening and closing filesIn C++, if we want to open a file, we must first obtain a

stream.(objects)Opening of files can be achieved in two ways:

1.using the constructor function of the stream classsyntax : stream streamobject(“name of filename”);

2.using the function Open( )Syntax : stream streamobject; streamobject.open(“name of filename”);

A file is closed by disconnecting it with the stream it is associated with.

Syntax : streamobject.close()

Page 9: Files in c++

Types of FilesFiles are of two types. 1. ASCII file or Text File :

Those files created by storing characters

2. Binary file : Those files created by storing a block of memory

Page 10: Files in c++

The concept of file modes:

It describes how a file is to be used• to read from it• to write to it• to append it• to read and write and so on.

Syntax : streamobject.open( “filename”, file-mode);

Page 11: Files in c++

File mode constantsSl.No File modes Meaning Stream

type1 ios :: in it opens file for reading ifstream2 ios :: out it opens file for writing ofstream

3 ios :: app It causes all output to that file to be appended to the end ofstream

4 ios :: ate It seeks to end-of-file upon opening of the file. ofstream

5 ios :: trunc Delete contents of the file if it exists ofstream

6 ios :: nocreateIt causes the open() functions to fail if the file does not already exist. It will not create a new file with that name.

ofstream

7 ios :: noreplace

It causes the open() functions to fail if the file already exist. This is used when we want to create a new file and at the same time

ifstream

8 ios :: binary It causes a file to be opened in binary mode.

ifstream, ofstream

Page 12: Files in c++

Reading and writing characters from / to disk

The functions put() and get() are used for manipulating a file character by character.These functions are members of ostream and istream respectively.put() is used for output to the file.get() is used for input from file.

Page 13: Files in c++

To create a File using put()#include<fstream.h>void main(){

ofstream outfile(“out.txt”);char str[]=“This is a text

file”;int i=0;while(str[i])

outfile.put(str[i++]);outfile.close();

}

Page 14: Files in c++

To read a File using get()#include<fstream.h>void main(){ char ch;

ifstream infile(“out.txt”);while(infile){ infile.get(ch);

cout << ch;}infile.close();

}

Page 15: Files in c++

Detecting End of File(eof())eof() is a member of ios class.

It returns a non-zero value if the end-of-file is encountered and a zero otherwise.

Page 16: Files in c++

Reading and writing class objects from / to disk

The functions write() and read() are usually used to transfer a block of data from and to the file.These functions are members of ofstream and ifstream respectively.write() is used for output to the file.read() is used for input from file.

Page 17: Files in c++

write() functionTo write to the fileIt takes two arguments

i.e., a pointer to the block andthe size of the block

Eg., stdfile.write((char *)&s, sizeof(student));

Page 18: Files in c++

read() functionTo get the contents from the fileIt takes two arguments

i.e., a pointer to the block andthe size of the block

Eg., stdfile.read((char *)&s, sizeof(student));

Page 19: Files in c++

Program to Create a student File#include <fstream.h>class student{

private : int regno, mark;char name[20];

public:void getdata();

};

Page 20: Files in c++

void student :: getdata(){

cout << “\nEnter reg. number: “;

cin >> regno;cout << “\nEnter Name of

Student:”;gets(name);cout << “\nEnter Marks:”;cin >> marks;

}

Page 21: Files in c++

void main(){ student ob;

fstream stdfile;stdfile.open(“stud.dat”,ios::out);char flag;do{ ob.getdata();

stdfile.write((char *)&ob, sizeof(student));cout << “\n Continue ? y/n”;cin >> flag;

} while(flag==‘Y’ || flag==‘y’);stdfile.close();

}

Page 22: Files in c++

Program to Display a student File#include <fstream.h>class student{

private : int regno, mark;char name[20];

public:void getdata();void display();

};

Page 23: Files in c++

void student :: getdata(){

cout << “\nEnter reg. number: “;

cin >> regno;cout << “\nEnter Name of

Student:”;gets(name);cout << “\nEnter Marks:”;cin >> marks;

}

Page 24: Files in c++

void student :: display(){

cout << “\nRegister number: “ <<regno;

cout << “\nName of Student:”<<name;

cout << “\nMarks:” <<marks;}

Page 25: Files in c++

void main(){ student ob;

fstream stdfile;stdfile.open(“stud.dat”,ios::in);stdfile.read((char

*)&ob,sizeof(student));while(stdfile){ ob.display(); stdfile.read((char

*)&ob,sizeof(student));}stdfile.close();

}

Page 26: Files in c++

Open for READING only H A I

Input pointer

Open for WRITING only

output pointer

Open for APPEND mode H A I

output pointer

Page 27: Files in c++

File Pointers for Random AccessWhen we open a file in more than one mode using

the fstream class, it is not necessary to close the file and open it again when we need to switch from one

mode to another.

But if we are writing and reading in different in different positions of the file, then, the stream pointers have to be positioned appropriately.

Each file object is associated with two integer values called the get_pointer and the put_pointer. These are also called the current postion. These values

specify the byte number in the file.

Page 28: Files in c++

Functions to move the File Pointer

seekg() Moves get_pointer(input pointer) to a specified location.

seekp() Moves put_pointer(output pointer) to a specified location.

tellg() Gives the current position to the get_pointer

tellp() Gives the current position to the put_pointer

Page 29: Files in c++

Example:

infile.seekg(15); It moves the file pointer to the byte number 15.

It is to be remembered that the bytes in a file are numbered beginning from zero. Therefore, the file pointer will be pointing to the 16th byte

in the file

Page 30: Files in c++

Example: ofstream ofile;ofile.open(“employee”,ios::app);int ptr = ofile.tellp();

On execution of these statements, the output pointer will be moved to the end of the file “employee” and the value of ptr will represent the number of bytes in the file.

Page 31: Files in c++

seekg() and seekp() functionsIt takes one or two arguments.If it takes two arguments, then

the first one is the relative offset, ie., the number of bytes the file pointer has to be moved (+ for forward and – for backward)The second argument is the position of the file pointer from where the offset is to be considered.

The default argument for this is the begIt can take values ios::beg, ios::end,

ios::cur

Page 32: Files in c++

Error Handling functionsThe different possible error situations are

enumerated belowThe file name used for a new file may be

an existing file nameA file which we are attempting to open for

reading may not exist.There may be no more room on the disk

for storing the newly created file.We may attempt to perform an operation

when the file is not opened for that purpose.

Page 33: Files in c++

Error Handling Functionseof() Returns non-zero if the end of file

is encountered while reading. Otherwise returns zero.

fail() Returns non-zero when an input or output operation has failed.

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

Page 34: Files in c++

Error Handling Functions

good()

Returns non-zero values if no error has occurred. When it returns zero, no further operations can be carried out.

clear()

Resets the error state so that further operations can be attempted