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

4. File Operations

file operation

Uploaded by

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

4. File Operations

file operation

Uploaded by

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

1

Fundamentals of Programming in C++


CoSc2031

Chapter 4

File Operations (File I/O) in C++

Mekonnen K.
(MSc) Email: [email protected]
Topics
Topics Subtopics
2
4: 4.1. Introduction
File 4.2. Stream classes
Operation 4.3. Writing and reading modes
(File I/O) 4.4. Writing to and reading from files
4.5. Types of files (Text and Binary)
4.6. File access methods (sequential and random-
access files)
4.7. Object Oriented Programming Concept
4.7.1 Programming Paradigm
4.7.2. Overview of programming principal
4.7.3. Class and Object
4.7.4. Pillars of Object-Oriented Programming
Concept
4.7.4.1. Encapsulation,
4.7.4.2. Abstraction,
4.7.4.3. Inheritance
4.7.4.5. Polymorphism
Introduction to File
o A file is a collection of related data stored in a
particular area on the disk . The data is stored in disk
using the concept of file .

o Programs can be designed to perform the read and write


operations on these files.

o In general a file is a sequence of bits, bytes, lines or records


whose meaning is defined by its user.

o C++ I/O occurs in streams, which are sequence of bytes.


Introduction to File (1)
o If bytes flows from device like a keyboard, a disk drive, etc to
main memory, this is called input operation.

o If bytes flow from main memory to devices like a display


screen, a printer etc. this is called output operation.

o In C++, file input/output facilities are implemented through a


header file fstream.h.
Stream in C++
o A stream is sequence of bytes. In C++, a stream is a general
name given to flow of data.
o Different streams are used to represent different kinds of data
flow.
o The three streams in C++ are as follows.
▪ Input Stream: The stream that supplies data to the program is known
as input stream.
▪ Output Stream: The stream that receives data from the program is
known as output stream.
▪ Error Stream: Error streams basically an output stream used by the
programs to the file or on the monitor to report error messages.
Stream in C++ (1)
Why File

o Permanent storage of data : - (all the message or value


printed with help of any output statements like cout,
printf , putchar are never available for future use ) .

o If there is a large amount of data generated as output


by a program, storing that output in file will help in easy
handling /analysis of the output , as user can see the
whole output at any time even after complete execution
of the program.
Why File (1)
o If we need lot of data to be inputted, user cannot
keep on typing that again and again for repeated
execution of program. In that case, all input data
can be once written in a file and then that file can
be easily used as the input file.

o The transfer of input – data or output – data from


one computer to another can be easily done by
using files.
File Stream classes
o Ifstream:- provides input operations and used for
reading from files. Contains open() with default input
mode. Inherits the functions get(), getline(), read(),
seekg() and tellg() function from istream.

o Ofstream:- provides output operations and used for


writing in files. Contains open() with default output
mode. Inherits put(), seekp(), teelp() and write()
function from ostream.
File Stream classes (1)
o Fsream :- provides support for simultaneous input
and output operations. Contains open() with default
input mode. Inherits all the function from isteram and
ostream classes through iostream.

o It is used for read from files and write to files.


General File I/O Steps

1. Include the header file fstream in the program.


2. Declare file stream variables.
3. Associate the file stream variables with the
input/output sources.
4. Open the file
5. Use the file stream variables with >>, <<, or other
input/output functions.
6. Close the file.
C++ streams
#include <fstream>
int main ()
{

ifstream fsIn;

ofstream fsOut;

fsIn.open("prog1.txt");

fsOut.open("prog2.txt");

fsIn.close();

fsOut.close();
return 0;
}
Opening a Files
 A file must first be opened before data can be read from
it or written to it.
 Opening a file associates a file stream variable
declared in the program with a physical file at the
source, such as a disk.
 In C++ there are two ways to open a file with the file
stream object.
o Opening file using constructor.
o Opening file using open ( ) member function
 The first method is preferred when a single file is used
with a stream. However for managing multiple files with
the same stream, the second method is preferred.
Opening Files using Constructors
 In order to access a file, it has to be opened either in read,
write or append mode.
 In all the three file stream classes, a file can be opened by
passing a filename as the first parameter in the constructor
itself.
 The syntax for opening a file using constructor is
streamclass_name file_objectname (“filename”);
 The syntax of opening a file for output purpose only using an
object ofstream class and the constructor is as follows.
ofstream ofstream_object(“file name”);
Example: ofstream fout (“results.dat”);
Opening Files using Constructors (1)
 The syntax of opening a file for input purpose only using an
object ifstream class and the constructor is as follows:
ifstream ifstream_object(“file name”);

 Example:
ifstream fin (“results.dat”);
Opening Files using open( )
 open( ) can be used to open multiple files that use the same
stream object.

 The syntax for opening a file using open ( ) member function


is as follows:
 file_stream_class stream_object;

 stream_object.open (“file_name”);

 The syntax of opening a file for output purpose member


function is as follows:
 oftream_object.open(“file name”);
Opening Files using open( ) (1)
 Example:

 ofstream outfile;

 outfile.open (“data”);

 outfile.open (“text.dat”);

 The syntax of opening a file for input purpose member


function is as follows:
 iftream_object.open(“file name”);

 Example: ifstream ifile;

 ifile.open (“data”);
Opening Files using open( ) (2)
 To open a file for both input and output , we declare objects
of fstream class fstream is derived from both ifstream and
ofstream.

 The syntax for opening a file an object of type fstream class


and the constructor is as follows:
 fstream fstream-object(“file name’, mode);

 The syntax for opening a file an object of type fstream class


and the open( ) member function is as follows:
 fstream-object.open(“file name’, mode);
File Modes
 While using constructors or open( ), the files were created or
opened in the default mode.

 There was only one argument passed, i.e. the filename.

 C++ provides a mechanism of opening a file in different modes


in which case the second parameter must be explicitly passed.
 Syntax: stream_object.open(“filename”, mode);

 Example: fout.open(“data”, ios::app) // This opens the file data in the


append mode.
File Modes (1)
 The lists of file modes are:
File Modes (2)
 Example:

 fstreamfout (“text”, ios::out); // open text in output mode

 fstream fin(“text”, ios::in); // open text in input mode

 fout.open(“data”, ios::app) // This opens the file data in the append mode

 fout.open(“data”, ios::app | ios::nocreate) // This opens the file in


the append mode but fails to open if it does not exist
Validate the file before trying to access

First method Second method

By checking the stream variable; By using bool is_open() function.

If ( ! Mystream) If ( ! Mystream.is_open())

{ {
cout << “Cannot open file.\n ”; cout << “File is not open.\n ”;

} }
File I/O Example: Open the file with validation
First Method (use the constructor) Second Method ( use Open function)

#include <fstream> #include <fstream>


using namespace std; using namespace std;
int main() int main()
{ {
ofstream ofstream outFile;
outFile(“fout.txt");
outFile.open(“fout.txt”);
if(! outFile)
{
if(! outFile.is_open() )
Cout << “Cannot open {
file.\n ”; Cout << “Cannot open
return 1; file.\n ”;
} return 1;
return 0; }
} return 0;
}
Writing to a File

➢ While doing C++ programming, you write information to a


file from your program using the stream insertion
operator << just as you use that operator to output
information to the screen.
➢ The only difference is that you use an ofstream or
fstream object instead of the cout object.
➢ we are sending output to a file. So, we use ios::out.
➢ As given in the program, information typed inside the
quotes after "FilePointer <<" will be passed to output
file.
File I/O Example: Writing
First Method (use the Second Method ( use Open
constructor) function)
#include <fstream> #include <fstream>
using namespace std; using namespace std;
int main() int main()
{ /* declare and automatically open { // declare output file variable
the file*/ ofstream outFile;
ofstream outFile("fout.txt"); // open an exist file fout.txt
outFile.open("fout.txt”);
//behave just like cout, put the
word into the file
//behave just like cout, put the
outFile << "Hello World!"; word into the file
outFile << "Hello World!";
outFile.close();
outFile.close();
return 0;
} return 0;
}
Reading from a File
➢ You read information from a file into your program using
the stream extraction operator >> just as you use that
operator to input information from the keyboard.
➢ The only difference is that you use an ifstream or
fstream object instead of the cin object.
➢ we are reading input from a file. So, we use ios::in. As
given in the program, information from the output file is
obtained with the help of following syntax "FilePointer
>>variable".
Detecting End of file:
 Detecting end of file is necessary for preventing any further
attempt to read data from the file.
 eof( ) is a member function of ios class.
 It returns a non-zero (true) value if the end of file condition is
encountered while reading; otherwise returns a zero (false).
 Example:
ifstream fin;
if(fin.eof( ))
{
statements;
}
 This is used to execute set statements on reaching the end of
the file by the object fin.
File I/O Example: Reading
Read char by char Read a line
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <string>
int main()
int main()
{ //Declare and open a text file
{//Declare and open a text file
ifstream openFile(“data.txt");
char ch; ifstream openFile("data.txt");
//do until the end of file string line;
while( ! OpenFile.eof() ) while(!openFile.eof())
{ { //fetch line from data.txt and put it
OpenFile.get(ch); // get one character in a string
cout << ch; // display the character getline(openFile, line);
} cout << line;
OpenFile.close(); // close the file }
openFile.close(); // close the file
return 0;
return 0;
}
}
Example writing into and Reading from file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
ofstream MyWriteFile("filename.txt"); // Create a text file
MyWriteFile << "Files can be tricky, but it is fun enough!"; // Write to the file
MyWriteFile.close(); // Close the file
// Create a text string, which is used to output the text file
string myText;
ifstream MyReadFile("filename.txt"); // Read from the text file
// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText))
{
cout << myText; // Output the text from the file
}
MyReadFile.close(); // Close the file
}
Closing File
 The member function close( ) on its execution removes the
linkage between the file and the stream object.

 Syntax: stream_object.close( );

 Example: ofstream.close( );

 ifstream.close( );
Input and output operation in text file
 The data in text files are organized into lines with new line

character as terminator.

 Text file need following types of character input and output

operations:

o put( ) function

o get( ) function
Input and output operation in text file (1)
 put ( )

 The put( ) member function belongs to the class ofstream and


writes single character to the associated stream.
 Syntax:
 ofstream_object.put(ch); // where ch is the character variable.
 Example:
▪ char ch=’A’;
▪ ofstream fout(“text.txt”);
▪ fout.put (ch);
 fout is the object of ofstream. Text is the name of the file. Value
at ch is written to text.
Input and output operation in text file (2)
 get ( )
 The get( ) member function belong to the class ifstream and
reads a single character from the associated stream.
 Syntax: ifstream_object.get (ch); // where ch is the character
variable
 Example:
 char ch;
 ifstream fin(“text.txt”);
 fin.get (ch);
 fin is the object of ifstream. Text is the name of the file. Reads a
character into the variable ch.
Input and output operation in text file (3)
 getline ( )
 It is used to read a whole line of text. It belongs to the class
ifstream.
 Syntax:
▪ fin.getline(buffer, SIZE)
 It reads SIZE characters from the file represented by the object
fin or till the new line character is encountered, whichever
comes first into the buffer.
 Example:
▪ char book[SIZE];
▪ ifstream fin;
▪ fin.getline (book, SIZE);
File pointers and their manipulation
o In C++, the file I/O operations are associated with the two file
pointers:
▪ Input pointer (get pointer)
▪ Output pointer (put pointer)
o We use these pointers to move through files while reading or
writing.
o Each time an input or output operation takes place,
appropriate pointer is automatically advanced.
▪ ifstream, like istream, has a pointer known as get pointer that
points to the element to be read in the next input operation.
▪ ofstream, like ostream, has a pointer known as put pointer that
points to the location where the next element has to be written.
File pointers and their manipulation (1)
o There are three modes under which we can open a file:
▪ Read only mode
▪ Write only mode
▪ Append mode
File pointers and their manipulation (2)
o When we open a file in read only mode, the input pointer is
automatically set at the beginning so that we read the file from
the beginning.

o When we open a file in write only mode, the existing


contents are deleted and output pointer is set at the
beginning.

o If we want to open an existing file to add more data, the file is


opened in append mode. This moves the file pointer to the
end of the file.
Functions for manipulation of file pointers
o To move file pointers to any desired position inside a file, file
stream classes support the following functions.
▪ seekg() - Moves get file pointer to a specific location

▪ seekp() - Moves put file pointer to a specific location

▪ tellg() - Returns the current position of the get pointer

▪ tellp() - Returns the current position of the put pointer

o The seekp() and tellp() are member functions of ofstream.

o The seekg() and tellg() are member functions of ifstream.

o All four functions are available in the class fstream.


Functions for manipulation of file pointers (1)
o seekg( )
o Move the get pointer to a specified location from the
beginning of a file.
o There are two types:
o seekg(long);
o seekg(offset, seekdir);
o The seekg(long) moves the get pointer to a specified
location from the beginning of a file.
o Example: inf.seekg(20);
o The seekg(offset, seekdir) has two arguments: offset and
seekdir.
o The offset indicates the number of bytes the get pointer is to
be moved from seekdir position.
Functions for manipulation of file pointers (2)
o seekdir takes one of the following three seek direction
constants.

Constant Meaning
ios::beg seek from beginning of file
ios::cur seek from current location
ios::end seek from end of file

o Syntax:

o stream_objectname.seekg(offset, origin_value);
Functions for manipulation of file pointers (3)
o Example : Some of the pointer offset calls and their actions
are shown in the following table

seekg( ) function option Action performed


object.seekg(0, ios::beg) Take get pointer to the beginning of the
file
object.seekg(0, ios::end) Go to end of the file

object.seekg(0, ios::cur) Stay get pointer at the current position.

object.seekg(m, ios::beg) Move forward by (m+1) bytes in the file

object.seekg(-m, ios::end) Go backward by m bytes from the file


end.
Functions for manipulation of file pointers (4)
o seekp( )

o Move the put pointer to a specified location from the


beginning of a file.

o There are two types:


o seekp(long);

o seekp(offset, seekdir);

o The seekp(long) moves the put pointer to a specified location


from the beginning of a file.
o Example: inf.seekp(20);
Functions for manipulation of file pointers (5)
o The seekp(offset, seekdir) has two arguments: offset and
seekdir.
o The offset indicates the number of bytes the put pointer is to
be moved from seekdir position.
o Syntax: stream_objectname.seekp(offset, origin_value);
seekp( ) function option Action performed

object.seekp(0, ios::beg) Go to beginning of the file for writing

object.seekp(0, ios::end) Go to end of the file for writing

object.seekp(0, ios::cur) Stay at the current position for writing

object.seekp(m, ios::beg) Move forward by m bytes from the


beginning for writing
object.seekp(-m, ios::end) Go backward by m bytes from the end
for writing
Functions for manipulation of file pointers (6)
o tellg ( ) and tellp( )
o tellg( ) returns the current position of the get pointer.
o Syntax:
position = ifstream_object.tellg( );
o Example:
int position
position= fin.tellg();
o tellp( ) returns the current position of the put pointer.
o Syntax:
position = ifstream_object.tellp( );
o Example:
int position
position= fin.tellp();
Functions for manipulation of file pointers
Example
Functions for manipulation of file pointers
Example (1)
Basic operation on binary file in C++
o Basic operation on binary file is:
o Searching

o Appending data

o Inserting data in sorted files

o Deleting a record

o Modifying data
Types of Files
 The C++ language supports two types of files:
• Text files
• Binary files
 A text file is a file that stores the information in ASCII characters.
 Each line of text is terminated by a special character, known as End of
Line (EOL) or delimiter.
 A binary file is a file that contains information in the same format as it
is held in memory.
 In binary files, no delimiters are used for a line and no translations occur
here.
Types of Files (1)
 A text file stores data in the form of alphabets, digits and
other special symbols by storing their ASCII values and are in
a human readable format. For example, any file with a .txt, .c,
etc extension.
 Whereas, a binary file contains a sequence or a collection of
bytes which are not in a human readable format.
 For example, files with .exe, .mp3, etc extension. It
represents custom data.
 A small error in a textual file can be recognized and
eliminated when seen. Whereas, a small error in a binary
file corrupts the file and is not easy to detect.
Types of Files (2)
 The basic difference between text files and binary files
is that in text files various character translations are
performed such as “\r+\f” is converted into “\n”,
whereas in binary files no such translations are
performed.

 By default, C++ opens the files in text mode.


File Access Modes
➢ Sequential Access File:- Sequential Access to a
data file means that the computer system reads or
writes information to the file sequentially, starting
from the beginning of the file and proceeding step by
step.
➢ Random Access /Direct Access:- Random Access to
a file means that the computer system can read or
write information anywhere in the data file.
Questions
1. Differentiate between ifstream and ofstream.

2. What is a stream? Mention any one stream used in C++.

3. Write any two member functions belonging to of stream class.

4. Write any two member functions belonging to if stream class.

5. Differentiate between read( ) and write( ).

6. Differentiate between put( ) and get( ) functions with reference


to binary files.
7. Give the function of put( ), get( ) and getline( ) with respect to
text files.
Questions (1)

8. Give the functions for the following:

a. get( ) b. getline( ) c. read( )


8. Mention the types of data files. Explain.

9. Explain any three modes of to open a file in C++.

10.Write the member function belong to ifstream.


Object Oriented Programming Concept
➢ OOP stands for Object-Oriented Programming.
➢ Procedural programming is about writing procedures or
functions that perform operations on the data, while object-
oriented programming is about creating objects that contain
both data and functions.
➢ Object-oriented programming has several advantages over
procedural programming:
• OOP is faster and easier to execute
• OOP provides a clear structure for the programs
• OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less code and
shorter development time
What are Classes and Objects?
 Classes and objects are the two main aspects of object-oriented
programming.
 Look at the following illustration to see the difference between class and
objects:
 example:
Another example:
 class class
 Fruit  Car
objects
 objects
 Volvo
 Apple  Audi
 Banana  Toyota
 Mango
 So, a class is a template for objects, and an object is an instance of a
class. When the individual objects are created, they inherit all the
variables and functions from the class.
C++ Classes/Objects

 C++ is an object-oriented programming language.


 Everything in C++ is associated with classes and objects, along
with its attributes and methods. For example: in real life, a car is an
object. The car has attributes, such as weight and color, and
methods, such as drive and brake.
 Attributes and methods are basically variables and functions
that belongs to the class. These are often referred to as "class
members".
 A class is a user-defined data type that we can use in our program,
and it works as an object constructor, or a "blueprint" for creating
objects.
C++ Classes/Objects
 Create a Class
 To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass // The class
{
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
C++ Classes/Objects

 Create an Object

 In C++, an object is created from a class. We have already


created the class named MyClass, so now we can use this to
create objects.

 To create an object of MyClass, specify the class name, followed


by the object name.

 To access the class attributes (myNum and myString), use the


dot syntax (.) on the object:
C++ Classes/Objects
 Example
 Create an object called "myObj" and access the attributes:
 lass MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print attribute values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
C++ Encapsulation

 The meaning of Encapsulation, is to make sure that "sensitive"


data is hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside
the class). If you want others to read or modify the value of a
private member, you can provide public get and set methods.

 Access Private Members

 To access a private attribute, use public "get" and "set" methods:


C++ Encapsulation
 Example
C++ Encapsulation
 Example explained
 The salary attribute is private, which have restricted access.
 The public setSalary() method takes a parameter (s) and assigns it to
the salary attribute (salary = s).
 The public getSalary() method returns the value of the private salary
attribute.
 Inside main(), we create an object of the Employee class. Now we can
use the setSalary() method to set the value of the private attribute to
50000. Then we call the getSalary() method on the object to return the
value.
 Why Encapsulation?
 It is considered good practice to declare your class attributes as
private (as often as you can). Encapsulation ensures better control of
your data, because you (or others) can change one part of the code
without affecting other parts
 Increased security of data
C++ Inheritance

 In C++, it is possible to inherit attributes and methods from one


class to another. We group the "inheritance concept" into two
categories:

 derived class (child) - the class that inherits from another


class

 base class (parent) - the class being inherited from

 To inherit from a class, use the : symbol.


C++ Inheritance
 In the example below, the Car class (child) inherits the attributes
and methods from the Vehicle class (parent):
// Base class // Derived class

class Vehicle { class Car: public Vehicle {


public:
public:
string model = "Mustang";
string brand = "Ford"; };

void honk() { int main() {


Car myCar;
cout << "Tuut, tuut! \n" ;
myCar.honk();
} cout << myCar.brand + " " +

}; myCar.model;
return 0;}
C++ Polymorphism

 Polymorphism means "many forms", and it occurs when we


have many classes that are related to each other by inheritance.
 Like we specified in the previous chapter; Inheritance lets us
inherit attributes and methods from another class.
Polymorphism uses those methods to perform different tasks.
 This allows us to perform a single action in different ways.
 For example, think of a base class called Animal that has a
method called animalSound(). Derived classes of Animals could
be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat
meows, etc.):
C++ Polymorphism
 Example
 // Base class // Derived class
class Animal { class Dog : public Animal {
public:
public:
void animalSound() {
cout << "The animal makes a sound \n"; void animalSound() {
} cout << "The dog says:
};
bow wow \n";
// Derived class
class Pig : public Animal { }
public: };
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
C++ Polymorphism
 Now we can create Pig and Dog objects and override the
animalSound() method:
 Example // Derived class
 // Base class class Dog : public Animal {
public:
class Animal {
void animalSound() {
public:
cout << "The dog says: bow wow \n";
void animalSound() {
}
cout << "The animal makes a sound };
\n";
} int main() {
}; Animal myAnimal;
// Derived class Pig myPig;
class Pig : public Animal { Dog myDog;
public:
void animalSound() { myAnimal.animalSound();
cout << "The pig says: wee wee \n"; myPig.animalSound();
} myDog.animalSound();
}; return 0;
}
! ! !
UR
FO
E R
P T
HA
C
O F
N D
E

You might also like