0% found this document useful (0 votes)
58 views31 pages

Lecture 6-Week6 - File Handling, Open, Read, Write, Ifstream, Ofstream, Fstream

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

Lecture 6-Week6 - File Handling, Open, Read, Write, Ifstream, Ofstream, Fstream

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

Object Oriented Programming

(CS1143)
Week 6

Department of Computer Science


Capital University of Science and Technology (CUST)
Outline

 Read from a file using ifstream


 Write to a File using ofstream
 Using fstream

2
Files for Storing Data

 Data stored in variables, arrays, and objects are temporary; they are
lost when the program terminates.
 To store the data created in a program permanently, you must save
them in a file on a permanent storage medium, such as a disk.
 C++ provides the ifstream , ofstream , and fstream classes for
processing and manipulating files.
 These classes are defined in the <fstream> header file.
 The ifstream class is for reading data from a file, the ofstream class is
for writing data to a file, and the fstream class can be used for
reading and writing data in a file.

3
Streams

 An input object in C++ is called an input stream and an


output object is called an output stream.
 cin (console input) is a predefined object for reading input
from the keyboard
 cout (console output) is a predefined object for outputting
characters to the console.
 Now we will learn how to read/write data from/to files

4
Absolute and Relative File Names

 An absolute file name contains a file name with its complete


path and drive letter.
 For example, c:\example\scores.txt is the absolute file name
for the file scores.txt on the Windows operating system.
 A relative file name is relative to its current working
directory.
 For example, “scores.txt” is a relative file name.
 We can use “./Directory Name/File Name” as a relative path
and store the file in a directory in the same folder where our
program is stored.

5
Writing to Files

6
ofstream

 The ofstream class can be used to write primitive data-type values,


arrays, strings etc. to a text file.

7
Program 1

8
Description

 line 2 includes the required header file.


 Line 7 creates an object, output, from the ofstream class
 Line 10 opens a file named scores.txt for the output object.
 If the file does not exist, a new file is created. If the file already exists, its
contents are destroyed without warning.
 Lines 13–14 write strings and numeric values to output
 The close() function (line 17) must be used to close the stream for the
object. Without it the data may not be saved properly in the file.

9
An alternate way to open an output stream

ofstream output("scores.txt");

 This statement is equivalent to

ofstream output;
output.open("scores.txt");

10
Reading Data

11
ifstream

 The ifstream class can be used to read data from a text file.

12
Program 2

13
Description

 The program creates an instance of ifstream and reads data from the
file scores.txt
 Line 8 creates an object, input , from the ifstream class for file
scores.txt.
 Lines 16 and 17 read strings and numeric values from the input file
 The close() function (line 22) is used to close the stream for the
object.
 It is not necessary to close the input file, but doing so is a good

14
Important Point

 To read data correctly, you need to know exactly how data are stored.
 For example, the previous program would not work if the file
contained score as a double value with a decimal point

15
Testing File Existence

 If the file does not exist when reading a file, your program will run
and produce incorrect results.
 You can invoke the fail() function immediately after invoking the open
function.
 If fail() returns true , it indicates that the file does not exist.

16
Program 3

17
Testing end of file

 If you don’t know how many lines are in the file and want to read
them all you can invoke the eof() function on the input object to
detect it.

18
Program 4

19
Description

 If there is no extra character or line at


the end, the output will be correct.
 If there is an extra character or an
extra line at the end it will read the
last element twice
 The reason for this is that when the
last number 10 is read, the file system
does not know it is the last number
because there are blank characters
after the last number. So, the eof()
function returns false
 When the program reads the number
again, the eof() function returns true,
but the variable number is not
changed, because nothing is read from
the file.
 The variable number still contains the
value 10 , which is added again to sum

20
Solution (P5)

21
Description

 The statement input >> number is actually to invoke an operator


function.
 This function returns an object if a number is read; otherwise it
returns NULL .
 NULL is a constant value 0 . C++ automatically casts it to a bool value
false when it is used as a condition in a loop statement or a selection
statement.
 If no number is read from the input stream, input >> number returns
NULL and the loop terminates.

22
getline() function

 There is a problem in reading data using the stream extraction


operator ( >> ) as data are delimited by whitespace.
 What happens if the whitespace characters are part of a string?
 We can use a function getline() for this purpose.

getline(ifstream& input, int string s, char delimitChar)

 The function stops reading characters when the delimiter character


or end-of-file mark is encountered.
 The third argument delimitChar has a default value '\n’. That means it
will read lines by default.

23
Program P6

24
get() and put()

 Two other useful functions are get and put .


 You can invoke the get function on an input object to read a
character and invoke the put function on an output object to write a
character.
 The program on the next slide prompts the user to enter a file and
copies it to a new file.

25
26
Description

 The program prompts the user to enter a source file name and a
target file name
 An input object for inputFilename is created in line 17 and an output
object for outputFilename in line 18.
 File names must be C-strings. inputFilename.c_str() returns a C-string
from string inputFilename .
 Lines 21–25 read characters repeatedly one at a time using the get
function and write the character to the output file using the put
function.

27
fstreams

28
fstreams

 We used ofstream to write data and ifstream to read data.


 We can use the fstream class to create an input or output stream.
 To open an fstream file, you have to specify a file open mode to tell
C++ how the file will be used.

29
Program P8

30
Description

 The program creates an fstream object in line 8


 It opens the file “city.txt” for output using the file mode ios::out in
line 10. After writing data the program closes the stream
 The program uses the same stream object to reopen the text file with
the combined modes ios::out | ios::app in line 14. The program then
appends new data to the end of the file
 Finally, the program uses the same stream object to reopen the text
file with the input mode ios::in in line 19. The program then reads all
data from the file.

31

You might also like