Topic:: Files & I/O

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 30

MODULE -5

TOPIC: FILES & I/O


CO5 Utilize I/O functionality to code basic file operations and [AN]
experiment with exception handling.

1
MODULE -5

OUTLINE
 Basic Input / Output in C++

 Input Stream

 Output Stream

2
MODULE -5

In C++ input and output is performed in the form of


sequence of bytes or more commonly known as streams.

Input Stream: If the direction of flow of bytes is from


device(for example: Keyboard) to the main memory then this
process is called input.

Output Stream: If the direction of flow of bytes is opposite,


i.e. from main memory to device( display screen ) then this
process is called output.

3
MODULE -5

C/C++ IO are based on streams


• sequence of bytes flowing in and out of the programs (just like
water and oil flowing through a pipe
• In input operations, data bytes flow from an input source (such
as keyboard, file, network or another program) into the
program
• In output operations, data bytes flow from the program to
an output sink (such as console, file, network or another
program)
• Streams acts as an intermediaries between the programs and
the actual IO device
4
formatted and unformatted IO
functions
In formatted or high-level IO
• bytes are grouped and converted to types such
as int, double, string or user-defined types.
In unformatted or low-level IO,
• bytes are treated as raw bytes and unconverted.

• Formatted IO operations are supported via


overloading the stream insertion (<<) and stream
extraction (>>) operators, which presents a
consistent public IO interface.
Header files available in C++ for Input
– Output operation are
iostream
iomanip
fstream

Module 4 Session 4 7
Header files available in C++ for Input
– Output operation are
iostream:
iostream stands for standard input output stream.
This header file contains definitions to objects like cin, cout,
cerr etc.
iomanip:
iomanip stands for input output manipulators.
• The methods declared in this files are used for
manipulating streams.
• This file contains definitions of setw, setprecision etc.
fstream:
This header file mainly describes the file stream.
• This header file is used to handle the data being read from
a file as input or data being written into the file as output.
the objects defined in the header
file iostream
Standard output stream (cout)
standard input stream (cin)
Un-buffered standard error stream (cerr)
buffered standard error stream (clog)

Module 4 Session 4 9
#include <iostream>

using namespace std;

int main( ) {
char sample[] = “ I Love Linuxc++";

cout << sample << " - A computer science portal for learners";

return 0;
}

using namespace std;

int main()
{
int age;
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: "<<age;

return 0;
}
Module 4 Session 4 10
The ostream Class
• The formatted output functions
(via overloaded stream insertion operator <<)
convert numeric values (such as int, double)
from their internal representations
• unformatted output functions
(e.g., put(), write()) outputs the bytes as they
are, without format conversion.

Module 4 Session 4 11
MODULE -5

The istream class


• In formatting input,
via overloading the >> extraction operator, it
converts the text form (a stream of
character) into internal representation
• In unformatting input,

such as get(), getlin(), read(), it reads the


characters as they are, without conversion.

12
MODULE -5

Unformatted Input/Output Functions

put(), get() and getline()


cout.put('A');
int inChar;
while ((inChar = cin.get()) != EOF)
{ // Read till End-of-file
cout.put(inchar); }

13
MODULE -5

Unformatted Input/Output Functions

read(), write() and gcount()


Read n characters from istream and keep in char array buf.
Write n character from char array.
Return the number of character extracted by the last unformatted
input operation

14
MODULE -5

Other istream function

Other istream functions - peek() and putback()


char peek (); //returns the next character in the input buffer
without extracting it.
istream & putback (char c); // insert the character back to the
input buffer.

15
MODULE -5

iomanip
• iomanip stands for input output manipulators.

• The methods declared in this files are used for manipulating


streams.

• This file contains definitions of setw, setprecision etc.

C++ provides a set of manipulators to perform input and output


formatting:

<iomanip> header: setw(), setprecision(), setbas(), setfill().

16
MODULE -5

CLASS TEMPLATES
cout << "|" << setw(5) << 123 << "|" << 123 << endl;

// | 123|123 // setw() is non-sticky. "|" and 123 displayed with default

cout << setfill('_'); // Set the fill character (sticky)


cout << setw(6) << 123 << setw(4) << 12 << endl; // ___123__12

cout << fixed << setprecision(2); // sticky


cout << "|" << 123.456789 << "|" << endl; // |123.46|
cout << "|" << 123. << "|" << endl; // |123.00|
cout << setprecision(0);
cout << "|" << 123.456789 << "|" << endl; // |123|

17
MODULE -5

File Input/Output

C++ provides the following classes to


perform output and input of characters
to/from files:

ofstream: Stream class to write on files


ifstream: Stream class to read from files
fstream: Stream class to both read and
write from/to files.
18
Open a file
In order to open a file with a stream object we use its member
function open:

open (filename, mode);


[file example.txt]
// basic file operations Writing this to a
#include <iostream>
#include <fstream>
file.
using namespace std;
int main () By default, opening an output
{ ofstream myfile; file creates a new file if the
myfile.open ("example.txt");
filename does not exist;
myfile << "Writing this to a file.\n";
myfile.close(); or truncates it (clear its
return 0; content) and starts writing as
}
an empty file.

19
File Output
The steps are:

• Construct an ostream object.


• Connect it to a file (i.e., file open) and set the mode of file
operation (e.g, truncate, append).
• Perform output operation via insertion >> operator
or write(), put() functions.
• Disconnect (close the file which flushes the output buffer) and
free the ostream object.

#include <fstream> .......


ofstream fout;
fout.open(filename, mode);
...... fout.close(); //

• OR combine declaration and open() ofstream fout(filename,


mode); 20
By default, opening an output file creates a new file if the filename does not
exist; or truncates it (clear its content) and starts writing as an empty file.
open(), close() and is_open()

File Modes
File modes are defined as static public member in ios_base superclass.
They can be referenced from ios_base or its subclasses –
we typically use subclass ios.

The available file mode flags are:

ios::in - open file for input operation


ios::out - open file for output operation
ios::app - output appends at the end of the file.
ios::trunc - truncate the file and discard old contents.
ios::binary - for binary (raw byte) IO operation, instead of character-based.
ios::ate - position the file pointer "at the end" for input/output.

21
File Input
The steps are:
 Construct an istream object.
 Connect it to a file (i.e., file open) and set the mode of
file operation.
 Perform output operation via extraction << operator
or read(), get(), getline() functions.
 Disconnect (close the file) and free the istream object.
#include <fstream> .......
fstream fin;
fin.open(filename, mode);

...... fin.close();

// OR combine declaration and open() ifstream fin(filename, mode);

22
// writing on a text file [file example.txt]
#include <iostream>
#include <fstream> This is a line.
using namespace std;
int main () This is another line.
{ ofstream myfile ("example.txt");
if (myfile.is_open())
{ myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

23
// reading a text file This is a line. This
#include <iostream> is another line.
#include <fstream>
#include <string>
using namespace std;
int main ()
{ string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
Else
cout << "Unable to open file"; return 0;
}

24
Random Access File
Random access file is associated with a file pointer, which can be moved directly to any
location in the file.

You can position the input pointer via seekg() and output pointer via seekp().
Each of them has two versions: absolute and relative positioning.
istream & seekg (streampos pos); // absolute position relative to beginning

istream & seekg (streamoff offset, ios::seekdir way);

// with offset (positive or negative) relative to seekdir:


// ios::beg (beginning), ios::cur (current), ios::end (end)

streampos tellg (); // Returns the position of input pointer

// Output file pointer (p for put)

ostream & seekp (streampos pos); // absolute


ostream & seekp (streamoff offset, ios::seekdir way); // relative

streampos tellp (); // Returns the position of output pointer

25
offset counted from the beginning of
ios::beg
the stream
ios::cur offset counted from the current position
offset counted from the end of the
ios::end
stream

26
/ obtaining file size size is: 40
#include <iostream> bytes.
#include <fstream>
using namespace std;
int main ()
{
streampos begin,end;
ifstream myfile ("example.bin", ios::binary);
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}

27
Set fill character
Sets c as the stream's fill character.

// setfill example
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setfill, std::setw
int main ()
{ std::cout << std::setfill ('x') << std::setw (10);
std::cout << 77 << std::endl; return 0;

}
Output:

xxxxxxxx77
28
Set decimal precision
Sets the decimal precision to be used to format floating-point values on
output operations.

// setprecision example
#include <iostream> // std::cout, std::fixed
#include <iomanip> // std::setprecision
int main ()
{ double f =3.14159;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n';
std::cout << std::fixed;
std::cout << std::setprecision(5) << f << '\n';
std::cout << std::setprecision(9) << f << '\n'; return 0;
}
Output:

3.1416
3.14159
3.14159
3.141590000
29
setw
Set field width

Sets the field width to be used on output operations.

#include <iostream> // #include <iomanip>


// int main ()
{
std::cout << std::setw(10);
std::cout << 77 << std::endl;
return 0;

77
Example

30

You might also like