0% found this document useful (0 votes)
11 views40 pages

Chapter Six Files and Stream

Introduction to files

Uploaded by

Abdi Nigatu
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)
11 views40 pages

Chapter Six Files and Stream

Introduction to files

Uploaded by

Abdi Nigatu
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/ 40

Chapter Six

Streams and External Files


Why are files used?
• All the programs we have looked at so far use input only from the keyboard, and output only
to the screen.
• If we were restricted to use only the keyboard and screen as input and output devices, it
would be difficult to handle large amounts of input data, and output data would always
be lost as soon as we turned the computer off.
• To avoid these problems, we can store data in some secondary storage device,
usually magnetic tapes or discs.
• Data can be created by one program, stored on these devices, and then accessed or
modified by other programs when necessary.
• To achieve this, the data is packaged up on the storage devices as data structures called files.
• A file is a collection of data stored together under a common name, usually on disk, magnetic
tape, USB drive, or CD
• A file is a container for data.
• Think of a file as a drawer in a file cabinet which needs to be opened and closed.
• Before you can put something into a file, or take something out, you must open the file (the
drawer). When you are finished using the file, the file (the drawer) must be closed.
Streams
• A stream as a channel on which data is passed from senders to receivers.
• Streams allow travel in only one direction.
• Data can be sent out from the program on an output stream, or received into the program
on an input stream.
• For example: at the start of a program, the standard input stream cin is connected to
the keyboard and the standard output stream cout is connected to the screen.
• The header file which lists the operations on streams both to and from files is called
fstream.
• Then it will be embedded in programs containing the "include" statement as follows:
#include <fstream>
• The essential characteristic of stream processing is that data elements must be sent to or
received from a stream one at a time, i.e. in serial fashion.
Cont…
• C/C++ IO are based on streams, which are 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 devices, in
such the way that frees the programmers from handling the actual devices, so as to
archive device independent IO operations.
I/O File Stream Objects and Functions
• The easiest way to think about a file is as a linear sequence of characters.
• To store and retrieve data outside a C++ program, two items are needed:
• A file
• A file stream object
• A file is a collection of data stored together under a common name, usually on disk,
magnetic tape, USB drive, or CD
• Each file has a unique file name, referred to as file’s external name
• We should Choose filenames that indicate the type of data in the file
• Two basic types of files exist:
• Text files (also known as character-based files)
• Binary files
File Stream Objects
• File stream: A one-way transmission path used to connect a file stored on a physical device,
such as a disk or CD, to a program
• Each file stream has its own mode that determines direction of data on transmission path:-
• That is, whether path moves data from a file to a program or from a program to a file
• Input file stream: File stream that receives or reads data from a file to a program
• Output file stream: File stream that sends or writes data to a file.
• For each file the program uses, regardless of file’s type, a distinct file stream object must be
created.
File Stream Functions
• Each file stream object has access to functions defined for its class
• Methods perform following functions:
• Connecting stream object name to external filename: opening a file
• Determining whether successful connection has been made
• Closing connection: closing a file
• Getting next data item into program from input stream
• Putting new data item from program onto output stream.
• When existing file is connected to input stream, file’s data is made available for input, starting
with first data item in file
• Called read mode or input mode
• File connected to output stream creates new file and makes file available for output
• Called output mode
• When opening file for input or output, check that connection has been established before
attempting to use file
Errors that are done
• Forgetting to open file before attempting to read from it or write to it
• Using file’s external name in place of internal file stream name when
accessing a file
• Opening file for output without first checking that file with the same name
already exists
• Opening existing file for output overwrites that file
• Not understanding that end of file is detected only after EOF marker has been
read and passed over
• Attempting to detect end of file by using character variables for EOF marker
• Any variable used to accept EOF marker must be declared an integer variable
Components of the iostream Class Library
• iostream class library consists of two primary base classes:
• streambuf
• ios
• streambuf class provides the file buffer
• ios class contains pointer to the file buffers provided by streambuf class and general
routines for transferring text data.
Stream operations
• To perform input and output, a C++ program:
1. Construct a stream object.
2. Connect (Associate) the stream object to an actual IO device (e.g., keyboard, console,
file, network, another program).

3. Perform input/output operations on the stream, via the functions defined in the
stream's pubic interface in a device independent manner.

❖ Some functions convert the data between the external format and internal format
(formatted IO); while other does not (unformatted or binary IO).
4. Disconnect (Dissociate) the stream to the actual IO device (e.g., close the file).
5. Free the stream object.
File Input/output (Header <fstream>)
• C++ handles file IO similar to standard IO.
• C++ provides the following classes to perform output and input 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.
• These classes are derived directly or indirectly from the classes istream and ostream. We have already
used objects whose types were these classes: cin is an object of class istream and cout is an object of
class ostream.
• In header:
• The class ofstream is a subclass of ostream;
• ifstream is a subclass of istream; and
• fstream is a subclass of iostream for bidirectional IO.
• To write to a file, you construct an ofsteam object connecting to the output file, and use the ostream
functions such as stream insertion <>, get(), getline() and read().
• File IO requires an additional step to connect the file to the stream (i.e., file open) and disconnect from
the stream (i.e., file close).
OPENING AND CLOSING A FILE
• A file can be opened in C++ by two methods:
1. By using the constructor of the stream class to be used
2. By using the open( ) function of the stream class to be used
• For reading entire lines of text :
• C++ provides get( ) and getline( ) functions as input member functions of the ifstream
class.
• It also provides a put( ) function as output member function of the ofstream class.
• In addition to text files, we can also read and write binary files.
• The major advantage of binary files is that they require less memory space for storage of data.
• Moreover, these files can be used to read or write structured data such as structures, class
objects etc.
• When we are finished with our input and output operations on a file, we shall close it so
that the operating system is notified and its resources become available again.
• Syntax: myfile.close();
File Output
❑ The steps are:
1. Construct an ostream object.
2. Connect it to a file (i.e., file open) and set the mode of file operation (e.g, truncate,
append).
3. Perform output operation via insertion >> operator or write(), put() functions.
4. Disconnect (close the file which flushes the output buffer) and free the ostream
object.
#include<fstream> ❖ By default, opening an output file
….. creates a new file if the filename does
ofstream fout; // create ostream object not exist; or truncates it (clear its
fout.open(filename, mode);// open file content) and starts writing as an
….. empty file.
fout.close();// close file

// OR combine declaration and open() ofstream


fout(filename, mode)
Cont.…
• Example:

❖ This program writes the contents into file


called First.txt.
❖ We create an object(fout) for ofstream
class.
❖ Then open First.txt in write mode to using
open() function to allow us to write into it.
❖ Then write into the file by using fout
object.
❖ Finally, the file is closed with close() function
Cont.…
Example 2: Reading the contents of First.txt
File Modes
• File modes are defined as static public member in ios_base superclass.
• They can be referenced from ios_base or its subclasses.
• The available file mode flags are:

• You can set multiple flags via bit-or (|) operator, e.g., ios::out | ios::app to append output at the end
of the file.
• For output, the default is ios::out | ios::trunc. For input, the default is ios::in
File Input
• The steps are:
1. Construct an istream object.
2. Connect it to a file (i.e., file open) and set the mode of file operation.
3. Perform output operation via extraction << operator or read(), get(), getline()
functions.
4. Disconnect (close the file) and free the istream object.

#include<fstream>
ifstream fin;
fin.open(filename, mode);
......
fin.close();
// OR combine declaration and open()
ifstream fin(filename, mode);
File Input
• Example:

• In this Example, the file is opened in read


mode.
• First, we created an object for ifstream class to
read the contents of the file.
• Then open the file in read mode using the
object name called readf.
• Then read the contents of the file character by
character until the end of the file is reached.
• Finally close the file.
Unformatted Input/Output Functions
• put(), get() and getline()
• The ostream's member function put() can be used to put out a char.
• put() returns the invoking ostream reference, and thus, can be cascaded.
• For example,
• // ostream class
• ostream & put (char c);
• // put char c to ostream
• // Examples cout.put('A'); cout.put('A').put('p').put('p').put('\n’);
• cout.put(65);
Stream Manipulators
• C++ provides a set of manipulators to perform input and output formatting:
1. header: setw(), setprecision(), setbas(), setfill().
2. header: fixed|scientific, left|right|internal, boolalpha|noboolalpha, etc.
• These are used with streams to modify the way data is displayed or read.
• setw() : Sets the width of the next output field. setw(n) sets the width to n
characters for the next output operation.
• setprecision() : Sets the number of significant digits to be displayed for floating-
point numbers.
• setprecision(n) controls the number of significant digits printed for a floating-
point value.
• fixed and scientificPurpose: Control the display of floating-point numbers in
either fixed-point or scientific notation.
• fixed: Forces the output of floating-point numbers in fixed-point notation.
• scientific: Forces the output of floating-point numbers in scientific notation.
States of stream
• The steam superclass ios_base maintains a data member to describe the states of the stream,
which is a bitmask of the type iostate.
• The flags are:
• eofbit: set when an input operation reaches end-of-file.
• failbit: The last input operation failed to read the expected characters or output
operation failed to write the expected characters, e.g., getline() reads n characters
without reaching delimiter character.
• badbit: serious error due to failure of an IO operation (e.g. file read/write error) or
stream buffer.
• goodbit: Absence of above error with value of 0.
• These flags are defined as public static members in ios_base. They can be accessed directly
via ios_base::failbit or via subclasses such as cin::failbit, ios::failbit.
• However, it is more convenience to use these public member functions of ios class:
• good(): returns true if goodbit is set (i.e., no error).
• eof(): returns true if eofbit is set.
• fail(): returns true if failbit or badbit is set.
Types of Disk File Access
• Your program can access files either in sequential manner or random
manner. The access mode of a file determines how one can read, write,
change, add and delete data from a file.
• A sequential file has to be accessed in the same order as the file was written.
This is analogues to cassette tapes: you play music in the same order as it was
recorded.
• In random access, unlike the sequential files, you can have random-access
to files in any order you want.
• Think of data in a random-access file as being similar to songs on compact
disc (CD): you can go directly to any song you want to play without having to
play or fast-forward through the other songs.
• You can perform three operations on sequential disk files. You can create disk
files, add to disk files, and read from disk files.
Creating a Sequential Access File
• Steps to create (or write to) a sequential access file:
1. Declare a stream variable name:
• ofstream fout; //each file has its own stream buffer
• ofstream is short for output file stream fout is the stream variable name
• Naming the stream variable "fout" is helpful in remembering that the information is going
"out" to the file.
2. Open the file:
• fout.open("scores.dat", ios::out);
• fout is the stream variable name previously declared "scores.dat" is the name of the file
ios::out is the steam operation mode (your compiler may not require that you specify the
stream operation mode.)
3. Write data to the file: fout<<grade<<"Mr. Spock\n";
• The data must be separated with space characters or end-of-line characters (carriage
return), or the data will run together in the file and be unreadable.
• Try to save the data to the file in the same manner that you would display it on the screen
Cont..
• If the iomanip.h header file is used, you will be able to use familiar formatting commands
with file output.
• fout<<setprecision(2);
• fout<<<setw(10)<<3.14159;
• 4. Close the file:
• fout.close( );
• Closing the file writes any data remaining in the buffer to the file, releases the file from the
program, and updates the file directory to reflect the file's new size.
• As soon as your program is finished accessing the file, the file should be closed. Most
systems close any data files when a program terminates. Should data remain in the buffer
when the program terminates, you may lose that data.
Writing to a sequential File
The most common file I/O functions are
▪ get()
▪ and put()
▪ You can also use the output redirection operator (<<) to write to a file.

This code writes the contents into the file.


Writing characters to sequential files
❖ A character can be written onto a file using the put() function.

• This code writes the


characters the user entered
into a file name1.txt using
put() function.
Reading from a sequential-access file
• Files you open for read access (using ios::in) must exist already, or C++ gives you an error
message. You can’t read a file that does not exist. Open() returns zero if the file does not
exist when you open it for read access.
• The following code displays the content of the file to the screen:
Reading characters from a sequential file
• We can read a characters from a file using get() function.
• NB. A space among characters is considered as a character and hence, the exact replica of
the file will be shown in the screen.
• The following program displays each character of the file to the screen
File Pointer and their Manipulators
❖ Each file has two pointers one is called input pointer and second is output pointer.
❖ The input pointer is called get pointer and the output pointer is called put pointer.
❖ In C++ there are some manipulators by which we can control the movement of the pointer.
❖ The available manipulators are:
1. seekg()
2. seekp()
3. tellg()
4. tellp()
❖ seekg(): this moves get pointer i.e input pointer to a specified location.
❖ Example: infile.seekg(5); move the file pointer to the byte number 5 from starting point.
❖ seekp(): this move put pointer (output pointer) to a specified location
❖ Example: outfile.seekp(5);
❖ tellg(): This gives the current position of get pointer (input pointer)
Cont…
❖ tellp(): this gives the current position of put pointer (output pointer)
❖ Example: fileout.open(“c:\\test.txt”,ios::app);
int length = fileout.tellp();
❖ By the above statement in length, the total number bytes of the file are assigned to
the integer variable length.
❖ Because the file is opened in append mode that means,the file pointer is the last part of
the file.
Cont…
• Example: let us see seekg() manipilator

• To point to the end of a data file, you can use the


seekg() function to position the file pointer at the
last byte.
• This statement positions the file pointer to the last
byte in the file. Fileobj.seekg(0L,ios::end);
• This seekg() function literally reads “move the file
pointer 0 bytes from the end of the file.”
• The file pointer now points to the end-of-file marker,
but you can seekg() backwards to find other data in
the file.
Cont.…
• Example: let us see seekg() manipilator

• The program is supposed to read “alph.txt” file backwards,


printing each character as it skips back in the file.
• Be sure that the seekg() in the program seeks two bytes
backwards from the current position, not from the beginning or
the end as the previous programs.
• The for loop towards the end of the program needs to perform a
“skip-two-bytes-back”, read-one-byte-forward” method to skip
through the file backwards.
Creating a Random-Access File
• Random access enables you to read or write any data in your disk file without
having to read and write every piece of data that precedes it.
• Generally you read and write file records.
• A record to a file is analogues to a C++ structure. A record is a collection of
one or more data values (called fields) that you read and write to disk.
• Generally you store data in the structures and write structures to disk.
• Functions fwrite and fread are capable of reading and writing arrays of data
to and from disk.
• The third argument of both fread and fwrite is the number of elements in
the array that should be read from or written to disk.
• Writing Data Randomly to a Random-Access File The program writes data to
the file .
• It uses the combination of fseek and fwrite to store data at specific locations
in the file.
Opening Random-Access Files
❖ There is really no difference between sequential files and random files in C++.
❖ The difference between the files is not physical, but lies in the method that you use to

access them and update them.


❖ The ostream member function write outputs a fixed number of bytes, beginning at a
specific location in memory, to the specified stream.
❖ When the stream is associated with a file, function write writes the data at the location in

specified by the “put” file position pointer.


❖ The istream member function read inputs a fixed number of bytes from the specified stream
into an area in memory beginning at the specified address.
❖ When the stream is associated with a file, function read inputs bytes at the location in the

file specified by the “get” file poison pointer.


❖ Syntax of write: fileobject.write((char*) & NameOfObject, sizeof(name of object))
Opening Random-Access Files
❑ Basic Steps for Random Access File Operations:

❖ Open the file using fstream with appropriate mode.


❖ Move the file pointer using seekg() or seekp().
❖ Perform read or write operations at the desired position.
❖ Close the file after operations are complete.
Writing randomly to a Random-access
•E file ❖ The code uses the combination of ostream function seekp
and write to store data at exact locations in the file.
❖ Function seekp sets the put file-position pointer to a
specific position in the file, then the write outputs the data.
❖ 1 is subtracted from the student id when calculating the
byte location of the record. Thus, for record 1, the file
position pointer is set to the byte 0 of the file.
❖ The istream function read inputs a specified number of bytes
from the current position in the specified stream into an
object.
❖ The syntax of read : read((char*)&name of object,
❖ sizeof(name of object));
❖ Function read requires a first argument of type char *.
❖ The second argument of write is an integer of type size
specifying the number of bytes to be read.
Reading a Random-access file
•E

❖ Here is a code that shows how to read a random-


access record from a file.
Program to Store and Retrieve Student Information
Program to Store and Retrieve Student Information in File
Program to Store and Retrieve Student Information
Explanation of the Above Code:
A. Class Definition:
❖ The Student class has three public members: studid, fname, and CGPA.
❖ It has two member functions:input() to read student data from the user.display() to print student data to the console.
B. Functions:
❖ saveStudents(Student students[], int count): This function takes an array of Student objects and their count as
parameters.
❖ It opens a file for writing and stores each student's information in the file.
❖ loadStudents(Student students[], int maxStudents): This function reads student data from the file and populates an
array of Student objects. It returns the number of students successfully loaded.
C. Main Function:
❖ The program first prompts the user to enter the number of students they want to add.
❖ It then collects student data using the input() method of the Student class.
❖ The entered student information is saved to a file using the saveStudents function.
❖ After saving, the program loads the student information from the file using the loadStudents function and displays it.

You might also like