0% found this document useful (0 votes)
21 views36 pages

Unit 4

The document provides an overview of file handling in C++, detailing the operations for creating, reading, writing, and modifying files using the C++ Standard Library. It explains the hierarchy of stream classes, including ios_base, basic_ios, basic_ostream, and basic_istream, and their roles in managing input and output operations. Additionally, it covers the usage of ifstream, ofstream, and fstream classes for file operations, along with examples of reading and writing data to files.

Uploaded by

driti s gowda
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)
21 views36 pages

Unit 4

The document provides an overview of file handling in C++, detailing the operations for creating, reading, writing, and modifying files using the C++ Standard Library. It explains the hierarchy of stream classes, including ios_base, basic_ios, basic_ostream, and basic_istream, and their roles in managing input and output operations. Additionally, it covers the usage of ifstream, ofstream, and fstream classes for file operations, along with examples of reading and writing data to files.

Uploaded by

driti s gowda
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/ 36

Unit 4

• A file is a collection of data or information that is stored on


a storage device (such as a hard drive, SSD, or cloud
storage) and identified by a unique name. Files are used to
organize and store data in a way that makes it accessible
for various applications, users, or systems.

• File handling in C++ allows you to perform various


operations like creating, reading, writing, and modifying files
using the C++ Standard Library. The file I/O (Input/Output)
operations are handled using classes defined in the
<fstream> header, such as fstream, ifstream, and ofstream.
File handling is used to store data permanently in a
computer. Using file handling we can store our data in
secondary memory (Hard disk).
How to achieve the File Handling
For achieving file handling we need to follow the
following steps:-
STEP 1-Naming a file
STEP 2-Opening a file
STEP 3-Writing data into the file
STEP 4-Reading data from the file
STEP 5-Closing a file.
C++ STREAM CLASSES HIERARCHY

This diagram shows the inheritance of stream-


related classes in C++. The central part of this
system is based on the ios_base class, and various
specialized stream classes like basic_ostream,
basic_istream, and their derived classes form the
I/O operation system.
• The ios_base class is the foundational class in C++ that
serves as the base for all stream classes that handle
input and output (I/O) operations. It is part of the I/O
system in the C++ Standard Library, which allows users
to interact with different types of streams, such as input
and output to the console, files, or other devices.

• Purpose of ios_base:The ios_base class does not directly


handle reading or writing data to a stream; instead, it
provides essential services that manage the behavior of
stream objects. This includes managing the stream's
state, formatting options, exception handling, and locale
settings.
basic_ios Class (Derived from ios_base):
•Purpose: This class is an extension of ios_base and introduces functionality for
actual input and output operations. It serves as the base class for all stream
classes that perform data transmission.
•Responsibilities:
•Buffer Management: Manages the buffer that stores data temporarily during I/O
operations.
•Stream State Management: Controls the state of the stream like "good," "fail," "eof"
(end-of-file), or "bad" states that indicate errors or issues in reading/writing operations.
•Formatting Flags: Controls the settings for formatting input and output, such as text
alignment, precision, etc.
basic_ostream Class (Derived from basic_ios):
•Purpose: This class is responsible for handling output (writing data) to streams. It is a base
class for all output stream classes.
•Responsibilities:
•Write Data: Provides the mechanism to write data to the stream (e.g., writing to the
console, files, or other output devices).
•Output Formatting: Inherited from basic_ios, it also controls formatting options
for output, such as precision, width, padding, etc.
•Buffer Management: Works with the underlying basic_streambuf to manage the
buffering of data being written to the output.
•Example of derived classes:
•basic_ofstream: Output to files.
•basic_ostream is often used in conjunction with std::cout for console output.
•This class declares output functions such as put() and write().
basic_istream Class (Derived from basic_ios):
•Purpose: This class is responsible for handling input (reading data) from streams. It serves
as the base class for all input stream classes.
•Responsibilities:
•Read Data: Provides the mechanism to read data from the input stream (e.g., from the
keyboard, files, or other input devices).
•Input Formatting: Inherited from basic_ios, it handles formatting for input (e.g.,
converting text to numbers).
•Stream State Handling: Manages stream states like whether the stream is open, if
reading has been successful, or if an error has occurred.
•Example of derived classes:
•basic_ifstream: Input from files.
•std::cin is an instantiation of basic_istream for standard input (keyboard).
•This class declares input functions such as get(), getline() and read().
basic_streambuf Class:
•Purpose: This is the buffer class that manages the intermediate data storage
for both input and output operations. It acts as an intermediary between the
stream object and the underlying I/O device (e.g., files, console).
•Responsibilities:
•Buffering Data: It holds data temporarily while it is being read or written.
This buffering improves efficiency by reducing the number of system calls
for I/O operations.
•Manage Input/Output Operations: It works with basic_ostream and
basic_istream to actually transfer data between the stream and
the device (e.g., writing bytes to a file or reading bytes from a
file).
ifstream Class (Input Stream Class):
•Purpose: The ifstream class is used for input operations, i.e., reading data from a file.
•Key Methods Inherited:
•get(): Reads a single character from the stream.
•getline(): Reads a line of characters from the stream, including spaces, and
stores it in a string.
•read(): Reads a specified number of bytes (or characters) from the stream
into a buffer.
•seekg(): Moves the "get" pointer to a specific position in the input stream
(used for seeking during file reading).
•tellg(): Returns the current position of the "get" pointer in the stream.
•Default Mode: When you open a file with ifstream, it opens in input mode by default
(i.e., for reading).
ofstream Class (Output Stream Class):
•Purpose: The ofstream class is used for output operations, i.e., writing data to a file.
•Key Methods Inherited:
•put(): Writes a single character to the stream.
•write(): Writes raw data (bytes) to the stream.
•seekp(): Moves the "put" pointer to a specific position in the output stream (used
for seeking during file writing).
•tellp(): Returns the current position of the "put" pointer in the stream.
•Default Mode: When you open a file with ofstream, it opens in output mode by default (i.e.,
for writing). If the file already exists, it will overwrite it unless you specify the std::ios::app flag to
append.
fstream (File Stream):
•This class combines both ifstream and ofstream, allowing reading from
and writing to the same file. It is derived from basic_iostream.
•Common methods:
•open(): Opens a file for reading or writing.
•close(): Closes the file when done.
•seekg() and seekp(): Moves the get and put pointers in the file
stream.
•Inherits all the functions from istream and ostream
classes through iostream.
FORMATTED AND UNFORMATTED I/O
• In C++. Using objects cin and cout for the input and the
output of data of various types is possible because of
overloading of operator >> and << to recognize all the
basic C++ types.
• The operator >> is overloaded in the istream class and
• The general
operator <<format for reading
is overloaded dataostream
in the from theclass.
keyboard:
• cin >> var1 >> var2 >> …. >> var_n;
• The class istream and ostream have predefined functions get()
and put(), to handle single character input and output
operations.

char data;

// get() return the character value and assign to data variable


data = cin.get();

// Display the value stored in data variable


cout.put(data);
Get()- The cin.get() function is used to read
a single character from the standard input
(keyboard).
Put() - The cout.put() function is used to write a
single character to the standard output (console).
#include <iostream> cin.get(inputChar);
using namespace std;
// Output the character using
int main() { cout.put()
char inputChar; cout<<"the entered
character is: ";
cout.put(inputChar);
cout << "Enter a character:
"; cout << endl;

// Read a character using return 0;


cin.get() }
Note the two versions of get(). The fi rst is cin.get(ch).
Here, the character read from the stream is bound to the
argument (ch). In the other case ch = cin.get(), the value
returned from the get() function is assigned to ch. There
are no arguments to the get() function at the moment
getline(), read(), and write()
Functions
• C has gets() and puts() functions for reading and writing
strings. They are better than using scanf() because
scanf() with %s option has a problem of terminating
when a white space is encountered. gets() does not
have this problem. These functions also provide easy
management than scanf() and printf().
• getline() reads whole line of text that ends with newline
character.
• It reads characters from the input stream until either n-1
characters have been read or a specified delimiter ('\n' by
default) is encountered.
• write() function displays an entire line

• Eg:
• char line[100];
• cin.getline(line, 11); // The input will be terminated after
reading 10 characters.
• cout.write(line, 11); // first arg represents name of string
and 2nd arg indicates number of characters to display
#include <iostream>
using namespace std;

int main() {
const int maxSize = 50;
char input[maxSize];

cout << "Enter a line of text: ";


cin.getline(input, maxSize); // Read up to 4 characters or until newline

cout << "You entered: " << input << endl;

return 0;
}
The write() function displays the entire line in one go and its syntax is similar to the getline()
function only that here cout object is used to invoke it.
• cin.read(char array, max size):
• cin.read() is used to read a specified number of
characters from the input stream (cin) and stores them
in a character array.
• It reads the specified number of characters, even if they
include spaces or newline characters.
• The read() function is a member function of the input
stream classes (like istream).
• It reads a specified number of characters (n) from the
input stream and stores them in the character array s.
• It reads the specified number of characters regardless
of encountering whitespace or newline characters.
#include <iostream>
using namespace std;

int main() {
const int maxSize = 5;
char input[maxSize];

cout << "Enter characters: ";


cin.read(input, maxSize); // Read 5 characters

cout << "You entered: " << input << endl;

return 0;
}
OPENING AND CLOSING FILES

• Before using a fi le, it must be initialized for usage. One


must initiate a request to the OS to open a fi le and get
a fi le handle
Defining Files
Files can be defined in three possible types.
1. ifstream <filename> (input file stream)
2. ofstream <filename> (output file stream)
3. fstream <filename> (I/O file stream)
• The ifstream file is a read-only file, and one can only
read from the file defined as ifstream.
• The ofstream file is an output-only file, and one can only
write to the file defined as ofstream.
• The fstream file is used for both input and output.
Opening Files
• Files can be opened using constructors and open
functions. Using constructors, one can open a fi le with
a statement such as
ofstream EntryFile("FewLines.dat")
• The fi le modes have not been specified. It is assumed
to be ios::out (output mode) when the object of
ofstream class (the EntryFile) is defined.
• Now, take a look at the following statement:
ifstream DisplayFile("FewLines.dat");
• Again, the file mode has not been specified. It is
assumed to be ios::in (input mode) for the objects of
ifstream class (the DisplayFile) in this case.
SL.No Mode Flag & Description

ios::app
1 Append mode. All output to that file to be
appended to the end.

ios::in
2
Open a file for reading.
ios::out
3
Open a file for writing.
Write a C++ program to create a text file, check file
created or not, if created write some text into the file and
then read the text from the file.
#include <iostream> cin.getline(text, sizeof(text));
#include <fstream>
using namespace std; // Writing to the file
file << text << endl;
int main() {
char text[200]; // Move the file pointer to the beginning for
fstream file; reading
file.seekg(0, ios::beg);
// Open the file in ios::out mode to create it if
it doesn't exist // Reading from the file using getline
// Open it in ios::in mode to read from it file.getline(text, sizeof(text));
file.open("example.txt", ios::out | ios::in);
// Display the text read from the file
if (!file) { cout << "Text read from the file: " << text
cout << "Error in creating/opening the << endl;
file!!!" << endl;
return 0; // Closing the file
} file.close();

cout << "File opened successfully." << endl; return 0;


cout << "Write text to be written to the file:" }
<< endl;
• Write a C++ program to read the contents from a text
file, count and display the number of alphabets present
in it.
• Note: If create one text file like vi example.txt file and
then write some content into it, save and exit. And then
execute the given below program.
#include <iostream>
#include <fstream> // Read characters from the file and
#include <cctype> // For isalpha function count alphabets
using namespace std; while (inFile.get(ch)) {
if (isalpha(ch)) {
int main() { alphabetCount++;
// Open the file for reading }
ifstream inFile("example.txt"); }

// Check if the file is opened successfully // Close the file


if (!inFile.is_open()) { inFile.close();
cout<< "Error: Unable to open the file for
reading." << endl; // Display the result
return 1; // Exit with an error code cout << "Number of alphabets in the
} file: " << alphabetCount << endl;

char ch; return 0; // Exit with success


int alphabetCount = 0; }

You might also like