0% found this document useful (0 votes)
26 views51 pages

Chapter-11 OOPC

Uploaded by

alex.moon268
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views51 pages

Chapter-11 OOPC

Uploaded by

alex.moon268
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Chapter-11

Working with files

Prepared By: Aayushi Chaudhari


Assistant Professor, CE,CSPIT.

5/13/2021 | U & P U. Patel Department of Computer Engineering 1


Contents
• Introduction
• Classes for file stream operations
• Opening and closing a file
• Detecting End of file
• File modes
• File pointers and their manipulations
• Sequential Input Output operations
• Error handling during file operations
• Command line arguments

Weightage: 10%
Hours: 4 Hours needed
5/13/2021 | U & P U. Patel Department of Computer Engineering
Introduction
Many real-time problems, stores large amount of data, which requires hard disk to store the
data.
Such kind of data is stored in the devices using the concept of files.

What is a file?

File is a collection of related data stored in a particular area on the disk.

Programs can be designed to perform read and write operations on these files.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Introduction
Program involves either or both of the following data communication:
• Data transfer between console unit and program
• Data transfer between the program and the disk file

The I/O system of C++ handles file operations which are very much similar to the console input and
output operations.

It uses file streams as an interface between the program and the files.
• Stream that supplies data to the program is known as input stream(reads data from file).
• Stream that receives data from the program is known as output stream(Writes data to file).
5/13/2021 | U & P U. Patel Department of Computer Engineering
File Input and Output Streams

Input stream: The stream that supplies data to the program is known as input stream. It extracts (or read) data
from file.
Output Stream: The stream that receives data from the program is known as output stream. It inserts (or
writes) data to the file.
5/13/2021 | U & P U. Patel Department of Computer Engineering
Classes for file stream operations

5/13/2021 | U & P U. Patel Department of Computer Engineering


Details of file stream classes

5/13/2021 | U & P U. Patel Department of Computer Engineering


File I/O steps
• Declare a file name variable.
• Associate the file name variable with the disk file name.
• Open the file
• Use the file
• Close the file

5/13/2021 | U & P U. Patel Department of Computer Engineering


Files and Streams
C++ views the file as sequence of bytes.
Ends with the end of file maker.

When file is opened, object is created for stream associated with it.
Cin, cout is created when <iostream> is included
Allows communication between program and file/device

5/13/2021 | U & P U. Patel Department of Computer Engineering


Opening a file
• For opening a file, we must first create a file stream and then link it to the filename.
• A file stream can be defined using the classes ifstream, ofstream, and fstream that are
contained in the header file fstream.
• The class to be used depends on read or write.
A file can be opened in two ways:
Using the constructor function of the class.
- Useful when we use only one file in the stream.
Using the member function open( ) of the class.
- Used when we wanted to manage multiple files using one stream.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Opening Files Using Constructor
This involves two steps:
• Create a file stream object to manage the stream using
appropriate class.
- The class ofstream is used to create output stream.
- The class ifstream to create input stream.
• We can initialize the file object with the desired filename.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Opening Files Using Constructor
ofstream outfile (“results”);
ifstream infile(“data”);

data file

results file

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example

5/13/2021 | U & P U. Patel Department of Computer Engineering


Opening Files Using Open( )
The open( ) can be used to open multiple files that use the
same stream object.
A set of files are processed in sequential manner.

file-stream-class stream-object;
stream-object.open ( “file_name” );

5/13/2021 | U & P U. Patel Department of Computer Engineering


Opening Files Using Open( )
ofstream outfile;
outfile.open(“DATA1”);
……..
outfile.close( );
outfile.open(“DATA2”);
………
outfile.close( );
.........
• The above program segment opens two files in sequence for writing the data.
• The first file is closed before opening the second one.
• A stream can be connected to only one file at a time.
5/13/2021 | U & P U. Patel Department of Computer Engineering
Example for reading data from existing file

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example for reading from and writing to file

5/13/2021 | U & P U. Patel Department of Computer Engineering


Detecting the end-of-file(two ways)
while (fin)
• An ifstream object fin returns a value 0 if any error occurs in the file operation including
the end-of-file condition.
• So the while loop may terminates when fin returns a value of zero on reaching the end-
of-file condition.
if(fin.eof() != 0) {exit(1);}
• eof( ) is a member of ios class.
• It returns a non-zero value if the end-of-file (EOF) condition is encountered, and a
zero, otherwise.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example-1

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example-1 cont..

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example-1 cont..

5/13/2021 | U & P U. Patel Department of Computer Engineering


File Modes
stream-object.open(“file_name”, mode);
• The second argument mode specifies the purpose for which
the file is opened. It is also called file mode parameter.
• Default values for these second parameters:

○ ios::in – for ifstream - reading only


○ ios::out – for ofstream - writing only

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example-Creating a File

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example-Writing to a File

5/13/2021 | U & P U. Patel Department of Computer Engineering


Various File Modes
ios::app -> Append to end-of-file
ios::ate -> Go to end-of-file on opening
ios::binary -> Binary file
ios::in -> Open file for reading only
ios::nocreate -> Open fails if the file does not exist
ios::noreplace -> Open files if the file already exists
ios::out -> Open file for writing only
ios::trunc -> Delete the contents of the file if it exists
fout.open(“data”, ios::app | ios :: nocreate)

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example of ios::app

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example of ios::ate

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example of ios::binary (for writing)

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example of ios::binary (for reading)

5/13/2021 | U & P U. Patel Department of Computer Engineering


File Pointer
Input Pointer (get pointer)
• The input pointer is used for reading contents of a given file
location.
Output Pointer (put pointer)
• The output pointer is used for writing to a given file location.

• Each time an input or output operation takes place, the appropriate


pointer is automatically advanced.
5/13/2021 | U & P U. Patel Department of Computer Engineering
File Pointer – Default Actions
• When a file opened in read-only mode, the input pointer is
automatically set at the beginning of the file.
• When a file is opened in write-only mode, the existing
contents are deleted and the output pointer is set at the
beginning.
• When a file is opened in append mode, the output pointer
moves to the end of file.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Default Actions

5/13/2021 | U & P U. Patel Department of Computer Engineering


Functions for Manipulations of File Pointers
How to move a file pointer in the desired location in
the file????
seekg( ) -> Moves get pointer (input) to a specified location.
seekp( ) -> Moves put pointer(output) to a specified location.
tellg( ) -> Gives the current position of the get pointer.
tellp( ) -> Gives the current position of the put pointer.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Seek Function with Absolute Position
Example: infile.seekg(10);

• Moves the file pointer to the byte number 10. The bytes in a file are numbered
beginning from zero. Therefore, the pointer pointing to the 11th byte in the
file.
ofstream fileout;
fileout.open(“Hello”, ios::app);
int p = fileout.tellp();
• The above statements will represent number of bytes in file.
5/13/2021 | U & P U. Patel Department of Computer Engineering
Seek Function with Specifying the Offset
seekg( offset, refposition);
seekp( offset, refposition);
• The parameter offset represents the number of bytes the file pointer is to be moved from
the location specified by the parameter refposition.
• The refposition takes one of the following three constants defined in the ios class:

ios : : beg -> start of the file


ios : : cur -> current position of the pointer
ios : : end -> end of the file

5/13/2021 | U & P U. Patel Department of Computer Engineering


Seek Function with Specifying the Offset
fout.seekg(0, ios : : beg); Go to start
fout.seekg(0, ios : : cur); Stay at the current position
fout.seekg(0, ios : : end); Go to the end of file
fout.seekg(m, ios : : beg); Move to (m+1)th byte in the file
fout.seekg(m, ios : : cur); Go forward by m bytes from the current position
fout.seekg(-m, ios : : cur); Go backward by m bytes from the current position
fout.seekg(-m, ios : : end) Go backward by m bytes from the end

5/13/2021 | U & P U. Patel Department of Computer Engineering


Sequential Input and Output Operations
put( ) and get( ) Functions
• The function put( ) writes a single character to the associated stream.
• The function get( ) reads a single character from the associated stream.

• The program request for the stream, and on receiving the stream, it writes character by
character, to the file using put() function in for loop.
• Length of the string is used to terminate the for loop.
• Similarly get function reads the characters from the file, till the end of file is reached.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example

5/13/2021 | U & P U. Patel Department of Computer Engineering


Sequential Input and Output Operations
write( ) and read( ) Functions
• The functions write( ) and read ( ) handle the data in binary form.
• The values are stored in the disk file in the same format in which
they are stored in the internal memory.
• An int takes two bytes to store its value in the binary form,
irrespective of its size.
• But a 4 digit int will take four bytes to store it in the character form.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Sequential Input and Output Operations
infile.read((char *) &V, sizeof(V));
outfile.write((char *) &V, sizeof(V));
write( ) and read( ) functions take two arguments.
• First is the address of the variable V
• Second is the length of that variable in bytes.
• The address of the variable must be cast to type char * (pointer to character
type).

5/13/2021 | U & P U. Patel Department of Computer Engineering


Example

5/13/2021 | U & P U. Patel Department of Computer Engineering


Error handling during file operations
It is quite common that errors may occur while reading data from a file in C++ or writing data
to a file. For example, an error may arise due to the following:

• When trying to read a file beyond indicator.


• When trying to read a file that does not exist.
• When trying to use a file that has not been opened.
• When trying to use a file in an inappropriate mode i.e., writing data to a file that has been
opened for reading.
• When writing to a file that is write-protected i.e., trying to write to a read-only file.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Error handling functions during file operations
Function Return Value
int bad() It returns a non-zero (true) value if an invalid operation is
attempted or an unrecoverable error has occurred. Returns
zero if it may be possible to recover from any other error
reported and continue operations.
int fail( ) It returns a non-zero (true) value when an input or output
operation has failed.
int good() It returns a non-zero (true) value when no error has occurred;
otherwise returns zero (false).
int eof( ) It returns a non-zero (true) value when end-of-file is
encountered while reading; otherwise returns zero (false).
int clear( ) The clear( ) function used to reset the error state so that further
operations can be attempted.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Flag Bit

Flag Bit Meaning


badbit 1 when a fatal I/O error has occurred, 0 otherwise.

failbit 1 when a non-fatal I/O error has occurred, 0 otherwise

goodbit 1 when no error has occurred, 0 otherwise

eofbit 1 when end-of-file is encountered, 0 otherwise.

5/13/2021 | U & P U. Patel Department of Computer Engineering


int bad( )

5/13/2021 | U & P U. Patel Department of Computer Engineering


int fail( )

5/13/2021 | U & P U. Patel Department of Computer Engineering


int eof( )

5/13/2021 | U & P U. Patel Department of Computer Engineering


#include <iostream> #include <fstream> using namespace std; int main() { fstream file; file.open("my_file.txt", ios::in); cout << "goodbit: " << file.good() << endl; string da

int good( )

5/13/2021 | U & P U. Patel Department of Computer Engineering


Command-line arguments
If any input value is passed through command prompt at the time of invoking the program is
known as
command line argument.
• It is a concept to passing the arguments to the main() function by using command prompt.
• In Command line arguments application main() function will takes two arguments

1. argc
2. argv

5/13/2021 | U & P U. Patel Department of Computer Engineering


Command-line arguments
Syntax:
int main(int argc, char *argv[] )
➢ argc: argc(argument counter) represents the number of arguments in the command line
including program name.

➢ argv[]: argv[](argument vector) is an array of char type pointers that points to the
command-line-arguments.

5/13/2021 | U & P U. Patel Department of Computer Engineering


Thank You.

5/13/2021 | U & P U. Patel Department of Computer Engineering

You might also like