12.12.2012 Views

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

Teach Yourself Borland C++ in 14 Days - portal

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

124 Day 4<br />

NOTE<br />

One of the ifstream constructors takes a char* as a parameter so that you can provide a<br />

filename when you <strong>in</strong>stantiate the class. Us<strong>in</strong>g this constructor, l<strong>in</strong>es 12 and 13 could be<br />

condensed <strong>in</strong>to a s<strong>in</strong>gle l<strong>in</strong>e:<br />

ifstream <strong>in</strong>file(“readfil.cpp”);<br />

If you create the object this way, the call to open() is unnecessary because the file will<br />

automatically be opened from the constructor.<br />

TIP<br />

Don’t forget about the double backslash <strong>in</strong> constant str<strong>in</strong>gs! For<br />

example, if you wanted to open the WIN.INI file <strong>in</strong> the W<strong>in</strong>dows<br />

directory, you would have to use this:<br />

ifstream <strong>in</strong>file(“c:\\w<strong>in</strong>dows\\w<strong>in</strong>.<strong>in</strong>i”);<br />

I know I’ve mentioned this before, but I’ll guarantee you that at some<br />

po<strong>in</strong>t you’ll goof this up, so I want to drill it <strong>in</strong>to your head while I’ve<br />

got the opportunity.<br />

The call to close() on l<strong>in</strong>e 19 of List<strong>in</strong>g 4.4 is not strictly needed. The ifstream destructor<br />

checks whether the file was left open. If it was, the destructor calls close() to ensure that the<br />

file is closed before the <strong>in</strong>stance of the class is destroyed. In my programs I almost always call<br />

close() even though it is not strictly required. Explicitly call<strong>in</strong>g close() has the added benefit<br />

of document<strong>in</strong>g that the file is no longer needed.<br />

The program <strong>in</strong> List<strong>in</strong>g 4.4 conta<strong>in</strong>s a m<strong>in</strong>or bug. Due to the way the<br />

end of the file is determ<strong>in</strong>ed, the program will pr<strong>in</strong>t one blank l<strong>in</strong>e<br />

before the loop term<strong>in</strong>ates. In order to avoid the extra l<strong>in</strong>e, the loop<br />

would have to be written like this:<br />

while (!<strong>in</strong>file.getl<strong>in</strong>e(buff, sizeof(buff)).eof()) {<br />

cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!