0% found this document useful (0 votes)
22 views20 pages

CPP Slide5

This document discusses file input/output (I/O) in C++. It introduces some key concepts related to files in C++ like streams, modes, text vs binary files. It explains how to open, read from, write to, and close files using ifstream, ofstream and fstream. It also covers checking if a file opened successfully and reading/writing data line by line from a text file. The overall purpose is to explain the basic process of working with files programmatically in C++.

Uploaded by

Solomon Desalegn
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)
22 views20 pages

CPP Slide5

This document discusses file input/output (I/O) in C++. It introduces some key concepts related to files in C++ like streams, modes, text vs binary files. It explains how to open, read from, write to, and close files using ifstream, ofstream and fstream. It also covers checking if a file opened successfully and reading/writing data line by line from a text file. The overall purpose is to explain the basic process of working with files programmatically in C++.

Uploaded by

Solomon Desalegn
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/ 20

Chapter 5

File I/O

1 12/5/2017
Introduction
 Data hierarchy
0 and 1 (bits) –> Charcaters --> 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
2 12/5/2017
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

3 12/5/2017
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

4 12/5/2017
Introduction
 Two file streams based on mode
 Input file stream – mode designated as input
 Output file stream – mode designated as output

Disk
#include <ftream.h> Output file stream
int main()
{
…. Input file stream
return 0;
}
5 12/5/2017
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
 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
6 12/5/2017
Introduction
 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

7 12/5/2017
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

8 12/5/2017
C++ File I/O
 To perform file I/O, the header file fstream 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

9 12/5/2017
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
10 12/5/2017
Text File Processing
 File processing involves the following major steps
 Declaring file variable identifier
 Opening the file
 Processing the file
 Closing the file when process is completed.

11 12/5/2017
Using Files
1: To access file handling routines:
#include <fstream>

2: To declare variables that can be used to access file:


ifstream in_stream;
ofstream out_stream;

3: To connect your program's variable (its internal name) to an external file


(i.e., on the Unix file system):
in_stream.open("infile.txt");
out_stream.open("outfile.txt");

4: To see if the file opened successfully:


if (in_stream.fail())
{
cout << "Input file open failed\n";
exit(1); // requires <cstdlib>
}
12 12/5/2017
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();
13 out_stream.close(); 12/5/2017
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
 ifstream in ; //input stream
 ofstream out ; // output stream
 fstream io ; // input and output
14 12/5/2017
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
15 input 12/5/2017
Opening….
 The check can also made by using fail().
 Returns true if the open fails false otherwise
 E.g
ifstream in_file;
in_file.open(“test.txt”); // open a file named test.txt
for input
if(in_file.fail())
{
cout<<“\nThe file was not successfully opend”
exit(1); //exits the program – stdlib.h
 When we are finished with our input and output
operations on a file we have to close it using close()
 its resources become available again
16  E.g. myfile.close(); 12/5/2017
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
 E.g.
ofstream out ("inventory");  //ofstream out;
//out.open(“inventory”)

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


out << "Toastors" << 19.95 << endl;
out.close ( );
17 12/5/2017
#include <iostream>
#include <fstream>

int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
 This code creates a file called example.txt and inserts
a sentence into it in the same way we are used to do
with cout, but using the file stream myfile instead.

18 12/5/2017
#include <iostream>
#include <fstream>
#include <string.h>

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{ while (! myfile.eof() )
{ getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
o reads a text file and prints out its content on the screen
19 12/5/2017
Checking state flags
•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
12/5/2017
return true. 20

You might also like