Starting+Out+With+C+++From+Control+Structures+through+Objects+(6th+Ed)+Tony+Gaddis+(P1)

Page 175

Bismillah hiir Rehman nir Raheem-----------------------------Assalat o Wasalam o Alika Ya RasoolALLAH

i

Chapter 3 Expressions and Interactivity

Some operating systems limit the number of files that may be open at one time. When a program closes fil es that are no longer being used, it will n Ot deplete more of the operating system's resources than necessa ry.

us uf

144

Calling the file strea m object's close member funct ion closes a fi le. Here is an example:

Yo

QutputFile.close();

Writing Data to a File

You alread y know how to use t he strea m insertion operator «<) w ith the cout o bject to

write data to t he screen . It can a lso be used with fil e stream objects to write data to a file.

outputFile «

"I love c+ + programming";

az

Assuming outputFile is a file stream object, the fo llowing statement demonstrates using the « operator £0 write a string to a file:

Ri

This statement writes (he string " I love C++ programming" ro (he fi le assoc ia ted with o utputFi l e . As you ca n see, the stateme nt looks like a cout statement, except the file strea m object name replaces couto H ere is a statement that writes both a suing a nd t he contem s of a variable to a file: outputFile «

"Price: " «

price:

an

Writing Data to a File

ss

The statement above writes the strea m o f data ro outputFile exactl y as cout would write it to th e screen. Program 3-29 demonstrates openi ng a fil e, writing da ta to the fi le, and closing t he fi le.

,

ad

3 4 5 6

II This program writes data to a file. ' include <iostream> 'include <fstream> using namespace std:

int main () (

8 9

of stre am outputF ile: output File .open( "demofile. txt" ) ;

10

11

cout «

m

1 2

Ha

Progr am 3-29

" Now writing dat a to the file. \n" ;

,

m

12

II Write output File outputFile output File output File

13

"

uh a

15 16

"

great names to the file « "Bach\n" i « "Beethoven \n" : « "Mozart\n" ; « "Schubert\n" ;

18

19

II Close the file outputFile.c lose(); cout«"Oone . \n return 0 ;

M

20 21 22

23

h

;

}

To Read Online & Download: WWW.ISSUU.COM/SHEIKHUHASSAN


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.