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

OOP Unit 4 Notes

Notes of unit 4

Uploaded by

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

OOP Unit 4 Notes

Notes of unit 4

Uploaded by

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

1|Page

Unit – IV
Files and Streams
1. Data Hierarchy
When a computer is powered off, the contents of its main memory are lost. Therefore, to
preserve data, we store it on disks or similar permanent storage devices. Data in computer
systems follows a structured hierarchy to optimize storage, access, and processing.

Files and Storage

A file is a sequence of bytes stored in secondary (permanent) storage. Each file has a unique
name for identification and follows a specific data format. The essential features of a file
include:

 Name: For identification and access.

 Format: A predefined structure, allowing for consistent reading and writing.

 Executable: If the file is of an executable type, it can be loaded and run by the system.

To execute a file, it must be transferred to the main memory (RAM), where it is then referred
to as a program. This transfer process is handled by the I/O (Input/Output) system,
facilitating the movement of data between primary and secondary storage.
2|Page

Program Execution and Memory Transfer

1. Secondary Storage (File): The initial location where data and programs are stored
permanently.

2. Main Memory (Program): Temporary storage for active programs, allowing CPU
access for execution.

For program execution, files must be loaded from secondary storage to main memory by the
system’s I/O processes.

Data in computer system follows hierarchy as shown in Figure below:

Data Hierarchy

Hierarchy is bit → characters → field → record → file → database

1. Bits: The smallest data item in a computer. It has a value 0 or 1.

2. Characters: It is combination of bits, instead of working with 0 and 1, specific pattern


of bits assigned to a character, e.g. decimal number (0-9), letters (a-z, A-Z) and special
symbols.

3. Fields: A field is a combination of one or more related characters (or bytes) and is the
smallest unit of data a user accesses. A field name uniquely identifies each field. The
field size defines the maximum number of characters a field can contain.

4. Records: A record is a group of related fields. For example, a student record includes a
set of fields about one student.
3|Page

5. Files: A data file is a collection of related records stored on a storage medium such as
a hard disk or an optical disc.

6. Database: A database includes a group of related data files.

1.1 Stream and Files

Input and Output Streams in C++

In C++, input and output operations are handled as sequences of bytes, commonly referred to
as streams. These streams provide a structured way to perform input and output (I/O) by
directing data flow between memory and devices. C++ includes libraries that offer a range of
tools for handling I/O tasks efficiently.

Types of Streams

1. Input Stream: When data flows from a device (e.g., keyboard) into main memory, this
is referred to as an input stream.

2. Output Stream: When data flows in the opposite direction, from main memory to a
device (e.g., display screen), it’s termed an output stream.

Categories of Streams in C++

C++ supports two main types of streams based on data representation:

1. Text Stream:

o A text stream is a sequence of characters where the data is human-readable.

o Some characters, such as newline (\n) or tab (\t), are stored with system-
specific encoding, so the representation of the data may not directly map one-
to-one between the device file and the stream.

o For instance, a file containing a newline character on Windows (\r\n) may


differ from its representation on other operating systems (\n).

2. Binary Stream:

o A binary stream is a collection of bytes with a direct, one-to-one relationship


between bytes in the stream and bytes in the device file.
4|Page

o There is no character conversion, so the number of bytes in the stream matches


the exact byte count in the file, making binary streams ideal for non-text data
like images or executable files.

Both types of streams can function as input or output streams:

 Input Streams allow data to be read into a program.

 Output Streams enable data to be written from a program to a file or device.

Standard C++ Header Files for I/O

C++ provides several essential header files for input and output operations:

1. <iostream>:

o The <iostream> library includes standard input and output stream objects like
cin, cout, and cerr.

o cin (console input) is used for accepting user input, and cout (console output)
is used for displaying output on the screen.

2. <iomanip>:

o The <iomanip> library offers functions, known as input/output


manipulators, for formatting streams.

o It includes utilities like setw for setting the width of the output and
setprecision for defining the precision of floating-point numbers.

Formatted and Unformatted Input and Output Functions

In C++, input and output operations can be categorized into two types: formatted and
unformatted. These categories determine how data is processed when reading from or writing
to streams. Here’s a breakdown of both types along with examples.

1. Formatted Input/Output

Formatted Input/Output functions are used to read and write data in a way that respects the
specified formatting. These functions include cout and cin, which handle data according to
its type and format.

Examples:
5|Page

 Formatted Output: Using cout with manipulators like setw(),


setprecision(), and fixed.

#include <iostream>
#include <iomanip> // for setw and setprecision
using namespace std;

int main() {
double pi = 3.14159;
cout << fixed << setprecision(2); // Set fixed decimal format with
2 decimal places
cout << "Formatted output of pi: " << pi << endl;

cout << setw(10) << "Number" << endl; // Set width for output
cout << setw(10) << 42 << endl; // Right align output in a width
of 10
cout << setw(10) << 100 << endl;

return 0;
}
2. Unformatted Input/Output

Unformatted Input/Output functions are used to read and write data in a raw format, without
any formatting. This type of input/output is faster but does not handle type conversions or
formatting.

Examples:

 Unformatted Output: Using write() to write raw data to a file or output stream.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
char data[] = "Hello, World!";
6|Page

ofstream fout("output.bin", ios::binary); // Open a binary file


for output
fout.write(data, sizeof(data)); // Write raw data
fout.close();

return 0;
}
3. <fstream>:

o The <fstream> library is dedicated to file stream operations.

o It includes classes like ifstream (input file stream) and ofstream (output
file stream) for reading from and writing to files.

To use cin and cout for basic input and output, the <iostream> header file must be
included in your program.

1. Standard Output Stream (cout)

The standard output stream is typically linked to the display screen. In C++, cout (character
output) is an instance of the ostream class and is used to print data to the screen.

 The insertion operator (<<) is used with cout to send data to the output stream.

2. Standard Input Stream (cin)

The standard input stream generally refers to the keyboard. In C++, cin (character input)
is an instance of the istream class and is used to receive input from the user.

 The extraction operator (>>) is used with cin to retrieve data from the input stream.

Example of cin and cout:

#include <iostream>
using namespace std;

int main() {
int age;
cout << "Enter your age: "; // Prompting user
7|Page

cin >> age; // Taking input using cin


cout << "You are " << age << " years old." << endl; // Displaying
output
return 0;
}
1.2 Stream Errors

Stream Error Handling

C++ includes two streams specifically for handling errors:

1. Un-buffered Standard Error Stream (cerr):

o cerr is an instance of the ostream class.

o It outputs error messages directly to the display without using any buffering,
making it ideal for immediate error display.

2. Buffered Standard Error Stream (clog):

o clog is also an instance of the ostream class.

o Unlike cerr, clog uses a buffer. The error message is stored temporarily until
the buffer is full, providing a delayed output.

Example of cerr and clog:

#include <iostream>
using namespace std;

int main() {
int divisor;
cout << "Enter a divisor: ";
cin >> divisor;

if (divisor == 0) {
cerr << "Error: Division by zero is not allowed!" << endl; //
Unbuffered error output
clog << "Log: Division attempt with zero as divisor." << endl;
// Buffered error output
8|Page

} else {
cout << "Result: " << (10 / divisor) << endl;
}

return 0;
}
In this example:

 cerr displays an error message immediately if the user tries to divide by zero.

 clog stores a log message in a buffer and outputs it when the buffer fills, allowing for
efficient error logging over time.

1.3 Stream Classes

In simple terms, a stream in C++ is a “file in use.” While a file is static data stored on a device,
a stream represents this file as it is opened and used in memory for operations such as reading,
writing, or even sending data over a network. In essence, the stream is an interface between the
user and the actual device file, whether that file resides on a disk, tape, or flash drive.
Regardless of the source, streams in C++ provide the same set of operations to handle file data
consistently.

C++ offers a hierarchy of built-in classes in the <iostream> and <fstream> libraries, which
simplify file and stream operations. These classes provide functions to open files, manipulate
data, and save and close files after processing.

Stream Classes in C++

The stream classes are organized hierarchically, with ios as the top-level class that provides
the foundation for both input and output operations. Here is a breakdown of key stream classes
and their roles:

 ios class: This is the base class for handling both input and output operations. It is the
foundation of the stream hierarchy.

 istream class: Inherits from ios and provides functions for handling input, including
character and string input, with functions like get, getline, read, ignore, and
putback.
9|Page

 ostream class: Inherits from ios and handles output operations, providing functions
for outputting characters, strings, and objects using functions such as write and put.

 iostream class: Inherits from both istream and ostream (virtually), allowing it to
handle both input and output in a single object.

Example: Input and Output Operations

#include <iostream>
using namespace std;

int main() {
char x;

// Getting a single character from user input


cout << "Enter a character: ";
cin.get(x);

// Displaying the character back to the user


cout << "You entered: ";
cout.put(x);

return 0;
10 | P a g e

}
In this example:

 cin.get(x): Reads a single character from the standard input (keyboard).

 cout.put(x): Outputs the character to the standard output (screen).

Facilities Provided by Stream Classes

1. ios Class: Supplies essential input and output functions to all derived stream classes.

2. istream Class: Manages input operations. It includes functions such as get, getline,
read, ignore, and putback.

#include <iostream>
using namespace std;

int main() {
char x;
cin.get(x); // Reads a single character
cout << x;
return 0;
}
3. ostream Class: Manages output operations. It includes functions such as write and put.

#include <iostream>
using namespace std;

int main() {
char x;
cin.get(x); // Reads a single character
cout.put(x); // Outputs the character
return 0;
}
4. iostream Class: Manages both input and output operations. It combines functionalities
from both istream and ostream.
11 | P a g e

#include <iostream>
using namespace std;

int main() {
cout.write("ObjectOriented", 5); // Displays "Objec"
return 0;
}
Specialized Stream Classes for Assignment

C++ offers specialized stream classes that allow object reassignment:

 istream_withassign: This variant of istream enables object reassignment,


making it possible to reassign cin to another istream object at runtime.

Example: Demonstrating cin as an istream object.

#include <iostream>
using namespace std;

class Demo {
public:
int dx, dy;

friend void operator>>(Demo &d, istream &mycin) {


mycin >> d.dx >> d.dy;
}
};

int main() {
Demo d;
cout << "Enter two numbers dx and dy:\n";
d >> cin; // Equivalent to operator>>(d, cin);
cout << "dx = " << d.dx << "\tdy = " << d.dy;
return 0;
12 | P a g e

}
 ostream_withassign: This variant of ostream allows object reassignment, so
predefined objects like cout, cerr, and clog can be redirected at runtime.

Example: Demonstrating cout as an ostream object.

#include <iostream>
using namespace std;

class Demo {
public:
int dx, dy;

Demo() : dx(4), dy(5) {} // Constructor initializes dx and dy

friend void operator<<(Demo &d, ostream &mycout) {


mycout << "Values of dx and dy are:\n";
mycout << d.dx << " " << d.dy;
}
};

int main() {
Demo d;
d << cout; // Equivalent to operator<<(d, cout);
return 0;
}
In this example, operator << is overloaded to print the object’s data members dx and dy via
cout.

Summary

 ios: Base class for all stream operations.

 istream: Manages input.

 ostream: Manages output.


13 | P a g e

 iostream: Manages both input and output, inheriting features of istream and
ostream.

 istream_withassign and ostream_withassign: Specialized classes allowing


reassignment of cin, cout, and other standard streams.

1.4 Disk File I/O with Streams

File: A file is a collection of related data stored on a device, such as a disk, flash drive, or CD.
Every file is associated with a unique file name composed of a name and an extension (e.g.,
data.txt).

To interact with a file (read, write, or modify), we must first open it. C++ provides a set of
classes for handling files through streams, which offer standardized methods for file access.

Opening a File in C++

To open a file, we create an object of the relevant stream class and use the open() function.

Syntax: open(FileName, mode);

 FileName: A string specifying the full file path. If the file is in the same directory as
the program, only the file name is needed.

 Mode: An integer value that specifies the file access mode, such as read or write. These
modes are predefined constants in the ios class. The compiler assumes the mode based
on the stream class used.

Example:

#include <fstream>
using namespace std;

int main() {
ifstream fin; // Create ifstream object for input
fin.open("mydata.txt"); // Open file in input mode by default
fin.close(); // Close the file after operations
return 0;
}
14 | P a g e

The close() function saves the data to the file and closes it properly.

Different Mode Bits

Key Classes for File Handling

1. fstreambase: Base class for file streams. Contains the common open() and
close() functions and serves as a foundation for ifstream, ofstream, and
fstream.

2. ifstream: Provides input operations and opens files in read mode by default. It
inherits input-related functions such as get(), getline(), read(), seekg(),
and tellg() from istream.

3. ofstream: Provides output operations and opens files in write mode by default. It
inherits output-related functions such as put(), seekp(), tellp(), and write()
from ostream.

4. fstream: Supports both input and output operations by inheriting from both istream
and ostream, enabling simultaneous read and write access.

These classes and their functions enable us to perform the following operations on files:

 Open existing files or create new ones.

 Read, write, or modify data.

 Save changes.

 Close the file.

File Access Modes

When opening a file, we specify a file name and optionally a mode that determines the access
type. Each mode is a constant in the ios class, with the following common flags:

 ios::in – Open for reading (input) operations.

Ex. ifstream file;

file.open("example.txt", ios::in);

if (file.is_open()) {
15 | P a g e

// Code to read from file

 ios::out – Open for writing (output) operations.

Ex: ofstream file;

file.open("example.txt", ios::out);

if (file.is_open()) {

// Code to write to file

 ios::binary – Open in binary mode.

Ex: ifstream file;

file.open("example.txt", ios::in | ios::binary);

if (file.is_open()) {

// Code to read binary data from file

 ios::ate – Start at the end of the file. Without this flag, the initial position is the
beginning.

Ex: ifstream file;

file.open("example.txt", ios::in | ios::ate);

if (file.is_open()) {

// Initial position is at the end of the file

 ios::app – All output operations are appended to the end of the file.

Ex: ofstream file;

file.open("example.txt", ios::out | ios::app);


16 | P a g e

if (file.is_open()) {

// Code to write data to the end of file

 ios::trunc – Deletes previous content if a file is opened for output and already exists.

Ex: ofstream file;

file.open("example.txt", ios::out | ios::trunc);

if (file.is_open()) {

// Code to write data, previous content is erased

Combining Flags: Use the bitwise OR operator (|) to combine flags as needed.

Example: To open a file example.txt and append data:

ofstream file;

file.open("example.txt", ios::out | ios::app);

Default Modes

Each stream class has a default mode when no mode argument is provided:

 ofstream: ios::out

 ifstream: ios::in

 fstream: ios::in | ios::out

File Reading and Writing

To perform file I/O in C++, include the <fstream> header and create objects of the required
stream classes.

Writing to Files with ofstream

Functions in the ofstream class provide several ways to output data to files:

1. put(): Writes a single character to the file.


17 | P a g e

 Syntax: put(char);

 Example:

ofstream obj;

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

char ch1 = 'R';

obj.put(ch1); // Writes 'R' to the file

2. write(): Writes a block of data to the file, which can be a string or an array.

 Syntax: write(char* data, int length);

 Example:

char str[] = "Some text";

obj.write(str, strlen(str)); // Writes "Some text" to the


file

Reading from Files with ifstream

Functions in the ifstream class provide ways to read data from files:

1. get(): Reads the next character from the file.

o Syntax: get(char);

o Example:

ifstream obj;

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

char ch;

obj.get(ch); // Reads the next character from the file

2. getline(): Reads the next line from the file.

 Syntax: getline(char* str, int length);

 Example:
18 | P a g e

char str[50];

obj.getline(str, 50); // Reads up to 49 characters from


the file

3. read(): Reads a specified number of characters from the file into a variable.

 Syntax: read(char* data, int length);

 Example:

obj.read(str, 50); // Reads up to 50 characters into `str`

Example: Program using the C++ file input and output class with open(), get(), put(),
close() methods for opening, reading from and writing to a file. Use append mode while
opening the file for writing.

#include <iostream>
#include <fstream> // Include fstream for file handling
using namespace std;

int main() {
fstream file; // Declare a file stream object

// Open the file in both input and append mode


file.open("example.txt", ios::in | ios::app);

// Check if the file opened successfully


if (!file.is_open()) {
cout << "Error opening file!" << endl;
return 1; // Exit if file can't be opened
}

// Reading from the file character-by-character


cout << "Reading current contents of the file:\n";
char ch;
19 | P a g e

while (file.get(ch)) { // Read a character from file


cout << ch; // Print each character read
}

// Clear EOF flag to perform further operations


file.clear();

// Move the put pointer to the end for appending data


file.seekp(0, ios::end); // Sets the pointer at the end of the
file

// Writing new content to the file


cout << "\n\nAppending new content to the file.\n";
string newContent = "Appended text content.\n";
for (char c : newContent) {
file.put(c); // Write each character
}

// Close the file


file.close();
cout << "Data appended and file closed successfully.\n";

return 0;
}
Explanation of Code

 file.open("example.txt", ios::in | ios::app);: Opens example.txt


in input (ios::in) and append (ios::app) mode.

 file.get(ch);: Reads a single character from the file.

 file.put(c);: Writes each character of the string to the file.

 file.close();: Closes the file after reading and writing.


20 | P a g e

1.4 File Pointers, and Error Handling in File I/O

When a file is opened, it’s associated with two pointers:

 Get pointer (get): Used for reading data from the file.

 Put pointer (put): Used for writing data to the file.

The file pointers start at specific positions based on the mode, and by default, they move
forward as reading or writing occurs. C++ provides several functions to manipulate and control
these pointers.

Functions for Operating File Pointers

1. seekg() – Positions the get pointer at a specified offset.

o Syntax: seekg(int offset, ios::seekdir start);

o The start parameter specifies the reference point, which can be:

 ios::beg – Beginning of the file

 ios::cur – Current position in the file

 ios::end – End of the file

o Example:

obj.seekg(10, ios::cur); // Moves `get` pointer 10 chars


forward from current position

2. seekp() – Positions the put pointer at a specified offset.

 Syntax: seekp(int offset, ios::seekdir start);

 The start parameter works similarly to seekg().

 Example:

obj.seekp(-5, ios::cur); // Moves `put` pointer 5 chars


backward from current position

3. tellg() – Retrieves the current position of the get pointer.

 Syntax: int tellg();


21 | P a g e

 Example:

int position = obj.tellg();

tellp() – Retrieves the current position of the put pointer.

 Syntax: int tellp();

 Example:

int position = obj.tellp();

Note: For seekg() and tellg(), the file must be opened in read mode. For seekp() and
tellp(), it must be opened in write mode.

Program Demonstrating open(), seekg(), tellg(), and read() Functions

The following program demonstrates how to use various file I/O functions with a sample file
named "demo1.txt" containing the text ‘OBJECT ORIENTED PROGRAMMING’.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
char ch;
ifstream fin;
fin.open("/path/to/demo1.txt"); // Update with actual path

if (!fin) {
cout << "Error opening file." << endl;
return 1;
}

// Read and display the first character


fin.read(&ch, sizeof(ch));
cout << "Char = " << ch << endl;
22 | P a g e

// Move `get` pointer 3 characters forward


fin.seekg(3, ios::cur);
fin.read(&ch, sizeof(ch));
cout << "Char = " << ch << endl;

// Move to 7th character from the start


fin.seekg(7, ios::beg);
fin.read(&ch, sizeof(ch));
cout << "Char = " << ch << endl;

// Move 5 characters back from current position


fin.seekg(-5, ios::cur);
fin.read(&ch, sizeof(ch));
cout << "Char = " << ch << endl;

cout << "Final position of get pointer: " << fin.tellg() << endl;

fin.close();
return 0;
}
Error and End-of-File Handling

End-of-File (EOF) Check

When reading files sequentially, it’s important to check for the end of the file to avoid reading
beyond it. C++ provides the eof() function for this purpose. It returns true (1) if the end
of the file has been reached; otherwise, it returns false (0).

 Syntax:

if (!obj.eof()) {

// Statements

}
23 | P a g e

 Example:

while (!fin.eof()) {

fin.get(ch);

cout << ch;

This approach ensures smooth file handling and prevents errors from attempting to read past
the end of the file.

1.5 Overloading the Extraction and Insertion Operators

In C++, the operators >> and << serve dual purposes. By default, they perform bitwise shifting,
but they are also overloaded to facilitate input/output operations with streams:

 Extraction Operator (>>): Overloaded to allow cin to read input from the standard
input stream.

 Insertion Operator (<<): Overloaded to allow cout to write output to the standard
output stream.

The insertion and extraction operators can be customized (overloaded) for user-defined classes,
enabling objects to interact directly with streams. These overloaded operators are often defined
as friend functions of the class to access private members.

Example:

#include <iostream>
using namespace std;

class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
24 | P a g e

friend ostream & operator << (ostream &out, Complex &c);


friend istream & operator >> (istream &in, Complex &c);
};

ostream & operator << (ostream &out, Complex &c){


out << c.real << "+";
out << c.imag << "i" << endl;
return out;
}

istream & operator >> (istream &in, Complex &c){


cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imaginary Part ";
in >> c.imag;
return in;
}

int main(){
Complex c1;
cin >> c1;
cout << "The complex number is ";
cout << c1;
return 0;
}
Overview of cin and cout

 cin: An instance of the istream class, cin uses the overloaded extraction operator
>> to take input from the standard input (keyboard).

 cout: An instance of the ostream class, cout uses the overloaded insertion operator
<< to output data to the standard output (monitor).

These objects help facilitate stream-based input and output, enabling flexible formatting.
25 | P a g e

Memory as a Stream Object (In-Memory Formatting)

In-memory formatting allows you to treat a portion of memory as a stream. This technique can
be useful, for instance, in GUI applications where formatted text needs to be displayed in a
dialog box. Using in-memory streams, data can be composed and formatted in memory before
being passed to functions that display it on the screen.

Fixed-Size Buffer

To use in-memory formatting, include the sstream header file. In a fixed-size buffer, a char*
buffer is created, and an ostream object is linked to this memory, allowing you to write data
to memory just as you would to a file.

Dynamic-Size Buffer

For dynamic buffers, an ostringstream object can be created without an associated buffer,
allowing the object to allocate memory as needed. This object expands to hold any amount of
data you write into it.

Example of Dynamic Buffer:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
ostringstream streamObj;

// Write data into the stream


streamObj << "Formatted data: ";
streamObj << 123 << " and " << 45.67;

// Convert stream content to a string


string result = streamObj.str();
cout << "In-Memory Stream Output: " << result << endl;
26 | P a g e

return 0;
}
In this example, the stream object automatically manages its size as data is inserted. This can
be particularly useful in applications where formatted text output is required for display on
various output devices.

1.6 Command-Line Arguments

C++ provides the ability to accept command-line arguments, allowing data to be passed to a
program directly from the operating system. This is particularly useful in command-line
interfaces like DOS or Linux.

Understanding the main Function with Arguments

To handle command-line arguments in a C++ program, the main function is defined with two
parameters:

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

 argc: Stands for "argument count." It holds the number of arguments passed,
including the program name.

 argv[]: An array of character pointers representing the arguments.

o argv[0] contains the program name (or an empty string if not available).

o argv[1] to argv[argc-1] store the command-line arguments.

o argv[argc] is a NULL pointer that marks the end of the argument list.

Each element in argv can be treated as a C-string, or argv can be accessed as a 2D character
array.

Example: Writing to a File Using Command-Line Arguments

This example demonstrates reading a file name from the command line and writing user-
provided content to it.

Assume a file named demo1.txt will be created or modified as specified by the user in the
command-line arguments.

Program Code:
27 | P a g e

#include <iostream>
#include <fstream>
using namespace std;

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


int no, marks;
char name[40];

// Check if the program received enough command-line arguments


if (argc >= 2) {
ofstream fout;

// The second argument (argv[1]) is the file name


fout.open(argv[1]);

// Prompt user for input


cout << "Enter Name: ";
cin.getline(name, 40);
cout << "Enter Roll No.: ";
cin >> no;
cout << "Enter Marks: ";
cin >> marks;

// Write the data to the file


fout << "Roll No.: " << no << endl;
fout << "Name: " << name << endl;
fout << "Marks: " << marks;
fout.close();

cout << "Data written to file..." << endl;


} else {
28 | P a g e

cout << "Please specify the file name as a command-line


argument." << endl;
}

return 0;
}
Running the Program

1. In the Command Line:

o Run the program with the file name as a command-line argument.

o Example: ./program_name demo1.txt

2. In IDE (like Visual Studio or Eclipse):

o Go to Run → Run Configurations → Arguments Tab and specify the file


name (e.g., demo1.txt).

o Click Run to execute the program.

Sample Output:

Enter Name: John

Enter Roll No.: 21

Enter Marks: 96

Data written to file...

This input is saved in demo1.txt with the following content:

Roll No.: 21

Name: John

Marks: 96

This example illustrates how C++ command-line arguments can be used to dynamically specify
file names and facilitate various file operations.

1.9 Printer Output


29 | P a g e

In C++, the printerstream class is a straightforward extension of the standard output


stream, enabling direct output redirection to a printer. This allows applications to print plain
text without needing additional formatting.

Overview of Printer Stream Options

When creating a printerstream instance, you have multiple configuration options:

1. Prompt the User for a Printer: The printerstream can prompt users to select a
printer.

2. Specify a Printer by Name: You can define a specific printer by its name.

3. Provide a Drawing Context: Optionally, you can use a drawing context if required by
the printer.

The output is sent to the printer when the printerstream instance is either disposed of or
when the end() method is called explicitly. This approach is straightforward, although limited
in functionality; page margins are the main customizable option.

Example Code

This example demonstrates how to use printerstream to print a simple document titled
"Test" and customize page margins.

#include "printerstream.h"
using namespace std;

int main() {
// Initialize output to a printer (e.g., PDFCreator)
printerstream<wchar_t> printer("PDFCreator");

// Set margins to 5% of the document width


printer.margins(page_margins * ((printer.page_width() / 100) *
5));

// Begin printing a new document titled "Test"


printer.begin("Test");
30 | P a g e

// Print text to the document


printer << "Hello World!";

// End the printing process (optional if disposing of the


instance)
printer.end();

return 0;
}
Explanation of Key Components

 Printer Selection: The constructor allows specifying the printer by name


("PDFCreator" in this case).

 Margin Customization: The margins() method adjusts margins to 5% of the


document’s width, providing control over text positioning.

 Document Creation: begin() initiates a new document titled "Test".

 Content Printing: Text output is directed to the printer using standard output
formatting (<< operator).

 Ending the Document: end() finalizes the print job and sends it to the printer
(optional if the instance will soon go out of scope).

Programs from Previous Year Papers:

1. Write a program to create file, read and write record into it. Every record contains
employee name, id and salary. Store and retrieve at least 3 data.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Employee {
31 | P a g e

int ID;
float salary;
string name;

public:
void input() {
cout << "Enter name: ";
cin.ignore();
getline(cin, name);
cout << "Enter ID: ";
cin >> ID;
cout << "Enter salary: ";
cin >> salary;
}

void display() const {


cout << "Name: " << name << endl;
cout << "ID: " << ID << endl;
cout << "Salary: " << salary << endl;
}

// Write the employee object to a text file


void writeToFile(ofstream &out) const {
out << name << endl;
out << ID << endl;
out << salary << endl;
}

// Read the employee object from a text file


void readFromFile(ifstream &in) {
getline(in, name);
in >> ID;
32 | P a g e

in >> salary;
in.ignore(); // Ignore the newline character after salary
}
};

int main() {
const char* filename = "employees.txt";

// Writing data to a text file


ofstream fout(filename);
if (!fout) {
cerr << "Error opening file for writing." << endl;
return 1;
}

Employee emp;
cout << "Enter information for 3 employees.\n";
for (int i = 0; i < 3; ++i) {
cout << "Employee " << (i + 1) << ":\n";
emp.input();
emp.writeToFile(fout);
}
fout.close();
cout << "\nData saved to file.\n\n";

// Reading data from a text file


ifstream fin(filename);
if (!fin) {
cerr << "Error opening file for reading." << endl;
return 1;
}
33 | P a g e

cout << "Reading employee data from file:\n";


for (int i = 0; i < 3; ++i) {
emp.readFromFile(fin);
cout << "Employee " << (i + 1) << ":\n";
emp.display();
cout << endl;
}
fin.close();

return 0;
}
2. Define a class Person that has three a ributes viz name, gender and age. Write a C++
Program that writes an object to a file and reads an object from a file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class Person {
string name;
char gender;
int age;

public:
// Method to input data for the person
void input() {
cout << "Enter name: ";
cin.ignore();
getline(cin, name);
cout << "Enter gender (M/F): ";
cin >> gender;
34 | P a g e

cout << "Enter age: ";


cin >> age;
}

// Method to display the person's data


void display() const {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}

// Write the person object to a text file


void writeToFile(ofstream &out) const {
out << name << endl;
out << gender << endl;
out << age << endl;
}

// Read the person object from a text file


void readFromFile(ifstream &in) {
getline(in, name);
in >> gender;
in >> age;
in.ignore(); // Ignore the newline character after age
}
};

int main() {
const char* filename = "person.txt";

// Writing data to a file


ofstream fout(filename);
35 | P a g e

if (!fout) {
cerr << "Error opening file for writing." << endl;
return 1;
}

Person person;
cout << "Enter information for the person:\n";
person.input();
person.writeToFile(fout);
fout.close();
cout << "\nData saved to file.\n\n";

// Reading data from a file


ifstream fin(filename);
if (!fin) {
cerr << "Error opening file for reading." << endl;
return 1;
}

cout << "Reading person data from file:\n";


person.readFromFile(fin);
person.display();
fin.close();

return 0;
}
3. Write a program to create files using constructor func on.
#include <iostream>
#include <fstream>
#include <string>
36 | P a g e

using namespace std; // Use the standard namespace

class FileCreator {
private:
ofstream file; // Output file stream

public:
// Constructor
FileCreator(const string& filename) {
file.open(filename); // Open the file
if (!file) {
cerr << "Error opening file: " << filename << endl;
} else {
cout << "File created: " << filename << endl;
// Write some sample data to the file
file << "This is a sample file created using a constructor
function.\n";
file << "Hello, World!" << endl;
}
}

// Destructor
~FileCreator() {
if (file.is_open()) {
file.close(); // Close the file
cout << "File closed." << endl;
}
}
};

int main() {
string filename;
37 | P a g e

// Get the filename from the user


cout << "Enter the filename to create: ";
getline(cin, filename);

// Create an instance of FileCreator


FileCreator myFile(filename);

return 0;
}
4. Write a program that returns the size in bytes of a program entered on the command line.
#include <iostream>
#include <fstream>
using namespace std;

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


char ch;
int count = 0;

if (argc >= 2) {
// Object to read source file
ifstream fin;

// Open source file


fin.open(argv[1]);
if (fin) { // If file exists
while (fin.get(ch)) { // Read character only if it is
successful
count++;
}
fin.close();
38 | P a g e

cout << "File Size = " << count << " Bytes\n"; // Added
space in the output
} else {
cout << "Error opening file: " << argv[1] << endl; //
Error message for file opening failure
}
} else {
cout << "Source file not found\n";
}
return 0;
}

You might also like