0% found this document useful (0 votes)
16 views33 pages

C++ File Input and Output Basics

This is chapter seven computer programming so you can use it for many purpose and find all information on this website

Uploaded by

hayuasamad2
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)
16 views33 pages

C++ File Input and Output Basics

This is chapter seven computer programming so you can use it for many purpose and find all information on this website

Uploaded by

hayuasamad2
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

In all our programs so far, the input stream is

associated with the keyboard, and the output


stream with the screen. Larger programs may need
additional streams, such as streams associated with
disk files or other devices (e.g., sensors, printers,
cameras, …).

Chapter 7: File Input – Output


COMPUTER PROGRAMMING
Introduction

 Data hierarchy
0 and 1 (bits)  Characters  field  Record  files 
database
 Files:
 Is a collection of data that is stored together under a common
name usually on a secondary storage device
 E.g. the C++ programs that you store on a disk
 Why use files?
 Convenient way to deal with large quantities of data
 Store data permanently (until file is deleted)
 Avoid having to type data into program multiple times
 Share data between programs
…introduction

 Terminology
 Input. Get input from/read a file.
 Output. Put data into/write a file
 To store and retrieve data on a file in C++ three items are
required:
 A file
 A file stream
 A mode
…introduction

 Files are physically stored on an external medium using a unique


name called external file name

 Streams is a one way transmission path that is used to connect a file


stored on a physical device to a program.

 I/O in C++ uses streams… flow of data into and/or out of a program

 A stream is a data type (like int, double), but with special properties.

 Associated with every file stream is a mode, which determines the


direction of data on transmission path [ To and from a file ]
…introduction
As we’ve said, the term stream refers to a flow of
 Two file streams based on bytes coming from a source into our program or from
mode our program towards a destination.
 Input file stream – mode If the flow is incoming (e.g., from the keyboard) it is
designated as input called an input stream, while if it is outgoing (e.g., to
 Output file stream – mode the screen) it is called an output stream.
designated as output

#include <fstream.h> Output file


stream
int main()
{
Disk
…. Input file stream
return 0;
}
…introduction

There are two types of streams

 Text stream
 A text stream is a sequence of characters
 character translations may occur as required by the host
environment
 e.g. a new line may be converted to a carriage return/linefeed pair
 may not be a one-to-one relationship between the characters that
are written
 Binary stream
 A binary stream is a sequence of bytes
 a one-to-one correspondence to those in the external device
…introduction

 To use files we need to know:


 how to "connect" file to program
 how to tell the program to read data
 how to tell the program to write data
 error checking and handling EOF
 How to “disconnect” file from program
 You associate (connect) a stream with a specific file by performing
an open operation
 Once a file is open, information can be exchanged between it and
a program – read and write operation
 All streams are the same but all files are not
…introduction

 You disassociate a file from a specific stream with a


close operation
 All files are closed automatically when the program terminates
normally
 Files are not closed when a program terminates abnormally
 If you close a file opened for output, then contents, if any, of its
associated stream are written to the external device
 This process is referred to as flushing the stream
 Each stream that is associated with a file has a file control structure
of type FILE
The standard streams

 When program starts execution, three streams are opened


automatically.

 stdin -- standard input -- cin

 stdout -- standard output -- cout

 stderr -- standard error -- cerr


C++ File I/O

 To perform file I/O, the header file fstream.h is required


 fstream.h defines several classes, including ifstream,
ofstream, and fstream
 ifstream - Can be used for File read/input operations

 ofstream - Can be used for File write/output operations

 fstream - Can be used for both read/write c++ file I/O operations

 These classes are derived form istream, ostream,


 istream and ostream are derived form ios
File processing

In file processing, files are generally


classified into two as:
 Text file
 its content is treated as a sequence of characters
 can be accessed sequentially
 E.g. the value int count 321 stored in three byte considering the digit
sequence ‘3’, ‘2’, ‘1’
 Binary file
 record sequence in a binary format
 E.g. the value int count 321 stored in two byte since int requires two byte to
store any of its value
 0000 0001 0100 0001
Text File Processing

 File processing involves the following major steps

1. Include fstream.h header file

2. Declaring file variable identifier

3. Opening the file

4. Processing the file

5. Closing the file when process is completed.


Using Files
1: To access file handling routines:
#include <fstream>
using namespace std; // to access the standard stream
2: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
3: To open the file
in_stream.open("[Link]");
out_stream.open("[Link]");
4: To see if the file opened successfully:
if (in_stream.fail())
{
cout << "Input file open failed\n";
exit(1); // requires <cstdlib>
}
…Using Files

5: To get data from a file (one option), must declare a variable to hold
the data and then read it using the extraction operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
6: To put data into a file, use insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and written in order – generally can't
back up.
7: When done with the file:
in_stream.close();
out_stream.close();
Opening and closing a file

 An open file is represented within a program by a stream object


 Any input or output operation performed on this stream object will be
applied to the physical file associated
 In C++, you open a file by linking it to a stream
 Before you can open a file, you must first obtain a stream
 There are three types of streams - DECLARING FILE STREAMS
 ifstream in ; //input stream
 ofstream out ; // output stream
 fstream io ; // input and output
Opening

 Once you have declared a stream, you associate it with a file by


using the method open().
 Prototype
 void open (const char *filename, int mode, int access = filebuf::penprot );
 The value of the mode determines how the file is opened
 E.g
ifstream in_file;
in_file.open(“[Link]”); // open a file named [Link] for input
Opening …

 It is good programming practice to check that the connection has


been established successfully before using it
 To check if a file stream was successful opening a file
 By calling to member is_open() with no arguments
 returns a bool value of true in the case that indeed the stream object is
associated with an open file, or false otherwise
 E.g.
 if (myfile.is_open()) { /* ok, proceed with output */ }
 ifstream myStream ( "myfile" ); // open file for input
Check and Use File Stream
 The check can also made by using fail().
 Returns true if the open fails false otherwise.
// basic file operations
#include <iostream>
#include <fstream>
This code creates a file called [Link] and inserts
a sentence into it in the same way we are used to do
using namespace std;
with cout, but using the file stream myfile instead.
int main () {
ofstream myfile;
[Link] ("[Link]");
myfile << "Writing this to a file.\n";
[Link]();
return 0;
}
 When we are finished with our input and output operations on a file we have to close it
using close()
 its resources become usable again E.g. [Link]();
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.

Set the initial position at the end of the file.


ios::ate
If this flag is not set, the initial position is the beginning of the file.

All output operations are performed at the end of the file,


ios::app
appending the content to the current content of the file.

If the file is opened for output operations and it already existed, its
ios::trunc
previous content is deleted and replaced by the new one.
ofstream, ifstream and fstream has
a default mode
class default mode parameter

ofstream ios::out

ifstream ios::in

fstream ios::in | ios::out


Reading and Writing Text Files

 Simply use the << and >> operators


 same way you do when performing console I/O
 except that instead of using cin and cout, you substitute
a stream that is linked to a file

ofstream out ("inventory");  //ofstream out;


//[Link](“inventory”)

out <<"Radios" << 39.95 << endl;


out << "Toastors" << 19.95 << endl;
[Link] ( );
if([Link]())
{

Checking state flags // An error occurred.


}
There are functions that check the state of a stream with bool return type

Function Description

bad() Returns true if a reading or writing operation fails. For example in the
case that we try to write to a file that is not open for writing or if the
device where we try to write has no space left.

fail() Returns true in the same cases as bad(), but also in the case that a
format error happens, like when an alphabetical character is extracted
when we are trying to read an integer number.

eof() Returns true if a file open for reading has reached the end.
good() It is the most generic state flag: it returns false in the same cases in
which calling any of the previous functions would return true.
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {

Writing Example ofstream myfile ("[Link]");


if (myfile.is_open())
{
[file [Link]]
This is a line. myfile << "This is a line.\n";
This is another line. myfile << "This is another line.\n";
[Link]();
}
else cout << "Unable to open file";
return 0;
}
// reading a text file
#include <iostream>
#include <fstream>
#include <string>

Reading - using namespace std;


int main () {
Example string line;
ifstream myfile ("[Link]");
This is a line. if (myfile.is_open())
This is another line.
{
while ( getline (myfile, line) )
{ cout << line << '\n'; }
[Link]();
}
else cout << "Unable to open file";
return 0; }
Random File Access - Get and Put
Pointers (Stream Positions)
 All i/o streams objects keep internally -at least- one internal position:
 These internal stream positions point to the locations within the
stream where the next reading or writing operation is performed.

 ifstream, like istream, keeps an internal get position with the location
of the element to be read in the next input operation.

 ofstream, like ostream, keeps an internal put position with the


location where the next element has to be written.

 Finally, fstream, keeps both, the get and the put position, like
iostream.
Get and Put Pointers

 These two member functions with no parameters return


a value of the member type streampos, which is a type
representing the current get position (in the case of tellg)
or the put position (in the case of tellp).
 tellg()
 return a value of the member type pos_type, which is an integer
data type representing the current position of the get stream
pointer
 tellp()
 return a value of the member type pos_type, which is an integer
data type representing the current position of the the put stream
pointer
There are functions that allow
us to change the position of
the get and put stream
pointers
 seekg() offset counted from the beginning of the
ios::beg
 the stream pointer is changed to stream
the absolute position for input
stream
 seekg ( offset, direction );
 the position of the get or put offset counted from the current position
ios::cur
pointer is set to an offset value of the stream pointer
relative to some specific point
determined by the parameter
direction
 seekp() offset counted from the end of the
ios::end
 the stream pointer is changed to stream
the absolute position for output
stream
 seekp ( offset, direction );

 the position of the put pointer is set


to an offset value relative to some
specific point determined by the // ... move to another location to read.
parameter direction [Link](old_pos); // Return back to the first location.
// obtaining file size
#include <iostream>
Example - #include <fstream>
GET FILE SIZE using namespace std;

int main () {
streampos begin,end;
ifstream myfile ("[Link]", ios::binary);
begin = [Link]();
[Link] (0, ios::end);
end = [Link]();
[Link]();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
Binary File Processing

 To perform binary operations on a file, it should be opened using the ios::binary mode
specifier.
 functions specifically designed to input and output binary data sequentially
 read ( memory_block, size );
 write ( memory_block, size );

 memory_block is of type "pointer to char" (char*)


 It represents the address of an array of bytes where
 the read data elements are stored
 from where the data elements to be written are taken
 size is an integer value that specifies the number of characters to be read or written
from/to the memory block
 There are other two functions - get ( ) and put ( )
get() and put()

 byte-oriented
 get ( ) will read a byte of data.
 put ( ) will write a bye of data.
 E.g
 istream & get( char & ch );
 read a single character from the associated stream and puts the value in ch,
and returns a reference to the stream
 ostream & put ( char ch);
 writes ch to the stream and returns a reference to the stream
# include <iostream.h>
# include <fstream.h>
ifstream::pos_type size;
char * memblock;
int main ()
{
ifstream file ("[Link]", ios::in|ios::binary|ios::ate); if (file.is_open())
{
size = [Link](); memblock = new char [size];
[Link] (0, ios::beg);
[Link] (memblock, size);
[Link]();
cout << "the complete file content is in memory";
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
Assignment 2:

Write maximum of 5 pages report


about application of binary file
processing in C++ with Examples
End of Chapter 7
END OF THE COURSE

You might also like