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

C++ Notes Unit 5

Unit 5 discusses file handling in C++, covering the definition of files, types (text and binary), and the concept of streams. It details classes for file operations (ifstream, ofstream, fstream), methods to open and close files, file modes, and error handling during file operations. Additionally, it introduces command-line arguments and provides example programs to illustrate these concepts.

Uploaded by

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

C++ Notes Unit 5

Unit 5 discusses file handling in C++, covering the definition of files, types (text and binary), and the concept of streams. It details classes for file operations (ifstream, ofstream, fstream), methods to open and close files, file modes, and error handling during file operations. Additionally, it introduces command-line arguments and provides example programs to illustrate these concepts.

Uploaded by

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

Unit 5 - Working with Files

What is a File?
A file is a collection of data stored in a particular area on the disk. Programs are
designed to perform read and write operations on these files.
Types of files:
A file can be Two types.
1. Text File
2. Binary File
By default files in C++ are considered as Text Files.

1. Text file:-
 Text File stores information in ASCII characters.
 In text files, each line of text is terminated with a special character known as EOL
(End of Line) character .
2. Binary file.
 Binary File stores information in Binary Format.
 Binary files are faster and easier for programs to read & write.

What is Stream in C++?


It refers to a sequence of bytes.
Every file is linked to a stream.
Each stream is associated with particular class.

List out and explain Classes for File stream operations in C++.

 In C++, file streams are used for input and output operations on files.
 The standard file stream classes are stored in <fstream> header file.
 The following Figure shows the file stream class hierarchy in C++.

1
In C++, files are mainly dealt by using below three classes, ifstream, ofstream, fstream
available in fstream header file.
1. ifstream
2. ofstream
3. fstream

1. ifstream:-
ifstream class is used to read the information from a file. It contains open() function
with default input mode.

Example:
ifstream object_name;
ifstream obj;
To read File use : ios::in
obj.open("rani.txt",ios::in);

2. ofstream
ifstream class is used to write information into file. It contains open() function with
default output mode.

2
Example:
ofstream object_name;
ofstream obj;
To read File use : ios::out
obj.open("rani.txt",ios::out);

3. fstream:
fstream class provides support for simultaneous input and output operations ie read &
write operation. Inherits all the functions from istream and ostream classes through
iostream.

Example:
fstream object_name;
fstream obj;

To read File use : ios::in


obj.open("rani.txt",ios::in);

To Write File use : ios::out


obj.open("rani.txt",ios::out);

4. filebuf:

Its purpose is to set the file buffers to read and write.

Example:
fstream fs(“tseek.data”, ios::in);
filebuf* fb = fs.rdbuf();
fb = fs.rdbuf();

3
How do you open and Close a File in C++?

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:

i. Open File Using the constructor function of the class.

ii. Open File Using the member function open() of the class

1. Opening File Using Constructors

The constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize
file stream objects with the filenames passed to them.

Syntax and Example:

filestream object_name("File_Name",ios::in);

ifstream fin("myfile", ios::in) ;

fin.close();

Here "ifstream" is the stream class, "myfile" is the file name and "fin" is the object name,
fin.close() is used to close the file.

2. Opening Files Using Open() Function

In this method, Open() Function is used to create a file as follows:

Syntax and Example:

fstream fin; // create an input stream with object fin

fin.open("myfile.txt", ios::in); // associate fin stream with file Master.dat

fin.close(); // close command.

Close()
Close() function is used to close a file.
Example:

fin.close(); // close command.

4
Discuss about different types of File Modes in C++.

The Concept of File Modes


The filemode describes how a file is to be used : to read from it, to write to it, to append
it, and so on.
Syntax:
stream_object.open("filename", (filemode) ) ;
Example:
ofstream fout;
fout.open("student.txt", ios :: app);
Above syntax will open a file in the append mode.

Types of Modes for file opening in C++


We can open a file using ofstream class with two parameters: filename and opening
mode. A file can be opened in different modes, as shown in the following table.

5
File Handling functions in C ++

1. open() : To create a file


2. close() : To close an existing file
3. get() : To read a single character from the file
4. put() : To write a single character in the file
5. read() : To read data from a file
6. write() : To write data into a file

Figure – Reference for Different File Modes and Functions

How do you detect End of File ?


We can detect when the end of the file is reached by using the member function eof()
It returns non-zero when the end of file has been reached, otherwise it returns zero.

The while(fin.get(ch)) - while loop terminates when if(fin.eof()) - fin object returns a
value of zero or reaching at teh end-of-file.

6
Example Program for EOF

First of all, create a text file, “example.txt”. Add the following content ("Hello How are
you") to it and then save the file in Bin Folder.

Coding:
#include<iostream.h>
#include<conio.h>
#include <fstream.h>

void main()
{
clrscr();
fstream fin("example.txt", ios::in) ;
char ch;
while (fin.get(ch))
cout << ch;
if (fin.eof())
cout << "[EoF reached]\n";
else
cout << " Error Reading]\n";
fin.close();
getch();
}

7
Discuss about Files Pointers and their Manipulations in C++.

 The file pointer indicates the position in the file.


 File has two associated pointers called input pointer (or get pointer) and output
pointer (or put pointer).
 Each time an input or output operation takes place, the pointer moves
automatically.

1. Input Pointer:
When we open a file in read only mode (ios::in), the input pointer automatically set at
the beginning of the file. So that we can read the file from starting position.

Output Pointer:
When we open file in write only mode (ios::out), the exsisting contents are deleted and
the output pointer is set at the beginning of the file. This enables us to write the file from
starting point of the file.

In Uppend Mode:

In case we want to open an existing file to add more data, the file is opened in "append"
mode which is move the file pointer at the end of the file.

8
Functions for Manipulation of File Pointer:

The File Stream Classes provides the following Four Functions to control & manipulate
the move of the get & put pointers.

1. Seekg()
2. Seekp()
3. tellg()
4. tellp()

1. Seekg()
It places the file pointer to the specified position in input mode of file.
Example:
file.seekg(4,ios::beg);

2. Seekp()
It places the file pointer to the specified position in output mode of file.
Example:
file.seekp(position -2);

3. tellg()
It Gives the current position of the get pointer in input mode of file.

Example:
int p=file.tellg();
cout<<"Tellg outpult:"<<p;

4. tellp()
Example:
It Gives the current position of the put pointer in output mode of file.
int position=file.tellp();

cout<<position;

Example Program for Seekg() & tellpg()


#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<iostream.h>

void main()
{
clrscr();
char name[80];
fstream file;

9
file.open("College",ios::out);
cout<<"Enter Name: ";
cin>>name;
file<<name;
file.close();
file.open("College",ios::in);
char c;

file.seekg(4,ios::beg);
file.get(c);
cout<<"Bye 3 from begining :"<<c;
int p=file.tellg();
cout<<"Tellg outpult:"<<p;
file.close();
getch();
}

Output:

Example Program for Seekp() & tellpp()


#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<iostream.h>

void main()
{
clrscr();
int position;
fstream file;
file.open("testing.txt",ios::out);
file.write("Hello",5);
position=file.tellp();
cout<<"Current Poisition of pointer is:"<<position<<endl;
file.seekp(position -2);
file<<"Bye";
getch();
}

10
Output:

File Output:

Discuss about Error Handling During File Operations in detail.


Following conditions may arise while dealing with files:
i. A file which we are attempting to open for reading does not exists.
ii. The file name used for a new file may already exists.
The below file handling functions are used to handle the errors:

1. File Opening Error Handling


Check whether the file is opened successfully using the is_open() function

Example:
if (!outfile.is_open())
{

cout << "Error: Could not open the file for writing!" << endl;

11
2. Read / Write Error Handling:

Check Read/Write Errors after opening a file successfully using fail() function.

if (outfile.fail())
{

cout << "Error writing to file!" << endl;

Example Program to check whether the File is exists or not


#include <iostream>
#include <fstream>
#include<conio.h>

void main() {
ifstream file("Student_info.txt");

if (!file) { // Equivalent to file.fail()


cout << "Error: File could not be opened!" << endl;

cout << "File opened successfully!" << endl;


file.close();
getch();
}

Output:
Error: File could not be opened!

The if(!file) condition check, whether the file is exists or not in Bin Directory. If the file does not exist,
then it will display the error.

12
Discuss Command-Line Arguments in C++.
Command-line arguments allow users to pass input values to a C++ program when it is
executed. These arguments are passed through the terminal or command prompt.
In C++, the main() function can take two parameters to handle command-line
arguments:

int main(int argc, char* argv[])

argc (Argument Count): Stores the number of arguments passed, including the program
name.

argv (Argument Vector): An array of character pointers (char*), where each element
represents a command-line argument.

Example Program:
#include<iostream.h>
#include<conio.h>
#include<string.h>

int main(int argc, char* argv[])


{
cout << "Number of arguments: " << argc << endl;

for (int i = 0; i < argc; i++) {


cout << "Argument " << i << ": " << argv[i] << endl;
}

return 0;
}

13
14

You might also like