Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Object Oriented Programming

using C++
CST-157
UNIT-III
Files
Chapter- 9

University Institute of Engineering


Course Objectives

•To apply the concept of Files in C++.

University Institute of Engineering


Contents
• Introduction to File streams
• Hierarchy of file stream classes
• File Types
• File opening Modes
• File operations
• File I/O
• Reading/Writing of files
• Random-access to files.

University Institute of Engineering


Introduction to Files
• A file is a collection on information, usually stored on a
computer’s disk.
• Information can be saved to files and then later reused.
• Computer programs are associated to work with files as it helps in
storing data & information permanently.
• File - itself a bunch of bytes stored on some storage devices.
• In C++ this is achieved through a component header file called
fstream.h
• The I/O library manages two aspects- as interface and for transfer
of data.

University Institute of Engineering


THE fstream.h HEADER FILE
• A stream is a general term used to name flow of data.
• Streams act as an interface between files and programs.
• They represent as a sequence of bytes and deals with the flow of
data.
• Every stream is associated with a class having member functions
and operations for a particular kind of data flow.
• All designed into fstream.h and hence needs to be included in all
file handling programs.

University Institute of Engineering


Figure 8.1 I/O to a file

University Institute of Engineering


File Handling Classes

Hierarchy Diagram
Figure 8.2 I/O Classes

University Institute of Engineering


FUNCTIONS OF FILE
STREAM CLASSES
•1.filebuf – It sets the buffer to read and write, it contains close()
and open() member functions on it.

•2.fstreambase – this is the base class for fstream and, ifstream and
ofstream classes. therefore it provides the common function to
these classes. It also contains open() and close() functions.

•3. ifstream – Being input class it provides input operations it


inherits the functions get( ), getline( ), read( ), and random access
functions seekg( ) and tellg( ) functions.

University Institute of Engineering


FUNCTIONS OF FILE STREAM
CLASSES
•4. ofstream – Being output class it provides output operations it
inherits put( ), write( ) and random access functions seekp( ) and tellp(
) functions.
•5. fstream – it is an i/o class stream, it provides simultaneous input
and output operations.

University Institute of Engineering


FILE TYPES
A File can be stored in two ways
• Text File
• Binary File

University Institute of Engineering


DIFFERENCE BETWEEN TEXT FILE AND BINARY FILE
TEXT FILE BINARY FILE
• When using a text file, we • When using a binary file we
write out separately each of write whole record data to the
the pieces of data about a file at once.
given record.
• but the numbers in the binary
• The text file will be file will not be readable in
readable by an editor. this way.
• For the text file we will use • For the binary file we will
the usual output use write function to write to
operator(<<) and will output the file.
each of the pieces of the
record separately.

University Institute of Engineering


FILE MODES
The File Mode describes how a file is to be used, to read from it, write
to it, to append and so on
• Syntax
Stream_object.open(“filename”,mode);

• ios::out: It open file in output mode (i.e write mode) and place the
file pointer in beginning, if file already exist it will overwrite the
file.
• ios::in It open file in input mode(read mode) and permit reading
from the file.
• ios::binary Opens a file in binary mode.

University Institute of Engineering


FILE MODES
• ios::trunc It truncates the existing file (empties the file).
• ios::nocreate If file does not exist this file mode ensures that no file
is created and open() fails.
• ios::app It open the file in write mode, and place file pointer at the
end of file i.e to add new contents and retains previous contents. If
file does not exist it will create a new file.
• ios::ate It open the file in write or read mode, and place file pointer
at the end of file i.e input/ output operations can performed
anywhere in the file.
• ios::noreplace If file does not exist, a new file gets created but if the
file already exists, the open() fails.

University Institute of Engineering


OPENING A FILE
• Before data can be written to or read from a file, the file must be
opened.
ifstream inputFile;
inputFile.open(“customer.dat”);

14
University Institute of Engineering
PROGRAM 1
// This program demonstrates the declaration of an fstream
// object and the opening of a file. OUTPUT:
#include <iostream.h> Enter the name of a file you
wish to open
#include <fstream.h> or create: mystuff.dat [Enter]
void main(void) The file mystuff.dat was opened.
{
fstream dataFile; // Declare file stream object
char fileName[81];
cout << "Enter the name of a file you wish to open\n";
cout << "or create: ";
cin.getline(fileName, 81);
dataFile.open(fileName, ios::out);
cout << "The file " << fileName << " was opened.\n";
}
15
University Institute of Engineering
OPENING A FILE
DECLARATION
• fstream dataFile(“names.dat”, ios::in | ios::out);

// This program demonstrates the opening of a file at the


// time the file stream object is declared.
#include <iostream.h>
#include <fstream.h>

void main(void)
{
fstream dataFile("names.dat", ios::in | ios::out);
cout << "The file names.dat was opened.\n";
}
Output:
The file names.dat was opened.
16
University Institute of Engineering
CLOSING A FILE
A File is closed by disconnecting it with the stream it is associated
with. The close( ) function is used to accomplish this task.
Syntax:
Stream_object.close( );

Example :
fout.close();

University Institute of Engineering


STEPS TO CREATE A FILE
1. Declare an object of the desired file stream class(ifstream, ofstream, or
fstream)
2. Open the required file to be processed using constructor or open function.
3. Process the file.
4. Close the file stream using the object of file stream.

University Institute of Engineering


EOF()
• This function determines the end-of-file by returning true(non-zero)
for end of file otherwise returning false(zero).

– Syntax
– Stream_object.eof( );

• Example :
• fout.eof( );

University Institute of Engineering


TEXT FILE FUNCTIONS
• get() – read a single character from text file and store in a buffer.
e.g file.get(ch);

• put() - writing a single character in textfile


e.g. file.put(ch);

• getline() - read a line of text from text file store in a buffer.


e.g file.getline(s,80);

University Institute of Engineering


PROGRAM TO CREATE A TEXT FILE
USING STRINGS I/O

1. #include<fstream.h>
2. void main()
3. {
4. char s[80], ch;
5. ofstream file(“myfile.txt”); //open myfile.txt in default output
mode
6. do
7. { cout<<”\n enter line of text”;
8. gets(s); //standard input
9. file<<s; // write in a file myfile.txt
10. cout<<”\n more input y/n”;
11. cin>>ch;
12. }while(ch!=’n’||ch!=’N’);
13. file.close();
14. } //end of main
University Institute of Engineering
BINARY FILE
FUNCTIONS
read( )- read a block of binary data or reads a fixed number of bytes
from the specified stream and store in a buffer.

Syntax :
Stream_object.read((char *)& Object, sizeof(Object));

e.g:
file.read((char *)&s, sizeof(s));
write( ) – write a block of binary data or writes fixed number of bytes
from a specific memory location to the specified stream.

Syntax :
Stream_object.write((char *)& Object, sizeof(Object));

e.g:
file.write((char *)&s, sizeof(s));
University Institute of Engineering
FILE POINTER
• file.seekg(-p,ios::end), or
• file.seekg(p,ios::cur) i.e to move to p byte position from beginning,
end or current position.
• seekp(): It places the file pointer to the specified position in output
mode of file.
e.g file.seekp(p,ios::beg); or
file.seekp(-p,ios::end), or file.seekp(p,ios::cur)
i.e to move to p byte position from beginning, end or current
position.

University Institute of Engineering


FILE POINTER
• tellg(): This function returns the current working position of the file
pointer in the input mode.
e.g int p=file.tellg();

• tellp(): This function returns the current working position of the file
pointer in the output mode.
e.g int p=file.tellp();

University Institute of Engineering


RANDOM ACCESS FILES
Random Access means non-sequentially accessing information in a file

25
University Institute of Engineering
QUESTIONS FOR PRACTICE
1. What do you mean by buffer synchronization?
2. Name the member functions which are used to check the state of a
stream (all of them return a bool value). Define their purpose as
well.
3. What is formatted and unformatted input and output.

University Institute of Engineering


PROGRAMS FOR
1.
PRACTICE
Write a program to check the size of a file using file handling
functions.
[Hint: use tellg() and seekg() functions].
2. Write a program to read an entire file and store that file in memory
block.
3. Test the methods read() and write() in the Account class. To do so,
write a program called Account_rw.cpp that
– initializes an array with account objects and stores the array in
a file
– reads the contents of the file to a second array and displays the
accounts in that array to allow you to check them.
Use binary mode for read or write access to the file.

University Institute of Engineering


References
• https://en.wikipedia.org/wiki/C_file_input/output
• https://doc.lagout.org/programmation/...++/C%2B%2B%20Files%2
0and%20Streams.p
• https://www.slideshare.net/nileshdalvi01/file-handling-39132164
• https://www.sitesbay.com/cpp/cpp-file-handling.pp
• cse.iitkgp.ac.in/~pallab/PDS-2011-SPRING/Lec-9.pdf

University Institute of Engineering


Unit-
Course Outcome:-Students will
3
1. Understand the concepts of files
2. Identify the various file modes,I/O operations on files.
To provide in-depth knowledge of how to access files using the
3. concept of programming

University Institute of Engineering

You might also like