1 |
424 |
jeremybenn |
|
2 |
|
|
|
3 |
|
|
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd"
|
4 |
|
|
[ ]>
|
5 |
|
|
|
6 |
|
|
|
7 |
|
|
|
8 |
|
|
|
9 |
|
|
|
10 |
|
|
|
11 |
|
|
|
12 |
|
|
ISO C++
|
13 |
|
|
|
14 |
|
|
|
15 |
|
|
library
|
16 |
|
|
|
17 |
|
|
|
18 |
|
|
|
19 |
|
|
|
20 |
|
|
|
21 |
|
|
Input and Output
|
22 |
|
|
Input and Output
|
23 |
|
|
|
24 |
|
|
|
25 |
|
|
|
26 |
|
|
|
27 |
|
|
|
28 |
|
|
Iostream Objects
|
29 |
|
|
|
30 |
|
|
To minimize the time you have to wait on the compiler, it's good to
|
31 |
|
|
only include the headers you really need. Many people simply include
|
32 |
|
|
<iostream> when they don't need to -- and that can penalize
|
33 |
|
|
your runtime as well. Here are some tips on which header to use
|
34 |
|
|
for which situations, starting with the simplest.
|
35 |
|
|
|
36 |
|
|
<iosfwd> should be included whenever you simply
|
37 |
|
|
need the name of an I/O-related class, such as
|
38 |
|
|
"ofstream" or "basic_streambuf". Like the name
|
39 |
|
|
implies, these are forward declarations. (A word to all you fellow
|
40 |
|
|
old school programmers: trying to forward declare classes like
|
41 |
|
|
"class istream;" won't work. Look in the iosfwd header if
|
42 |
|
|
you'd like to know why.) For example,
|
43 |
|
|
|
44 |
|
|
|
45 |
|
|
#include <iosfwd>
|
46 |
|
|
|
47 |
|
|
class MyClass
|
48 |
|
|
{
|
49 |
|
|
....
|
50 |
|
|
std::ifstream& input_file;
|
51 |
|
|
};
|
52 |
|
|
|
53 |
|
|
extern std::ostream& operator<< (std::ostream&, MyClass&);
|
54 |
|
|
|
55 |
|
|
<ios> declares the base classes for the entire
|
56 |
|
|
I/O stream hierarchy, std::ios_base and std::basic_ios<charT>, the
|
57 |
|
|
counting types std::streamoff and std::streamsize, the file
|
58 |
|
|
positioning type std::fpos, and the various manipulators like
|
59 |
|
|
std::hex, std::fixed, std::noshowbase, and so forth.
|
60 |
|
|
|
61 |
|
|
The ios_base class is what holds the format flags, the state flags,
|
62 |
|
|
and the functions which change them (setf(), width(), precision(),
|
63 |
|
|
etc). You can also store extra data and register callback functions
|
64 |
|
|
through ios_base, but that has been historically underused. Anything
|
65 |
|
|
which doesn't depend on the type of characters stored is consolidated
|
66 |
|
|
here.
|
67 |
|
|
|
68 |
|
|
The template class basic_ios is the highest template class in the
|
69 |
|
|
hierarchy; it is the first one depending on the character type, and
|
70 |
|
|
holds all general state associated with that type: the pointer to the
|
71 |
|
|
polymorphic stream buffer, the facet information, etc.
|
72 |
|
|
|
73 |
|
|
<streambuf> declares the template class
|
74 |
|
|
basic_streambuf, and two standard instantiations, streambuf and
|
75 |
|
|
wstreambuf. If you need to work with the vastly useful and capable
|
76 |
|
|
stream buffer classes, e.g., to create a new form of storage
|
77 |
|
|
transport, this header is the one to include.
|
78 |
|
|
|
79 |
|
|
<istream>/<ostream> are
|
80 |
|
|
the headers to include when you are using the >>/<<
|
81 |
|
|
interface, or any of the other abstract stream formatting functions.
|
82 |
|
|
For example,
|
83 |
|
|
|
84 |
|
|
|
85 |
|
|
#include <istream>
|
86 |
|
|
|
87 |
|
|
std::ostream& operator<< (std::ostream& os, MyClass& c)
|
88 |
|
|
{
|
89 |
|
|
return os << c.data1() << c.data2();
|
90 |
|
|
}
|
91 |
|
|
|
92 |
|
|
The std::istream and std::ostream classes are the abstract parents of
|
93 |
|
|
the various concrete implementations. If you are only using the
|
94 |
|
|
interfaces, then you only need to use the appropriate interface header.
|
95 |
|
|
|
96 |
|
|
<iomanip> provides "extractors and inserters
|
97 |
|
|
that alter information maintained by class ios_base and its derived
|
98 |
|
|
classes," such as std::setprecision and std::setw. If you need
|
99 |
|
|
to write expressions like os << setw(3); or
|
100 |
|
|
is >> setbase(8); , you must include <iomanip>.
|
101 |
|
|
|
102 |
|
|
<sstream>/<fstream>
|
103 |
|
|
declare the six stringstream and fstream classes. As they are the
|
104 |
|
|
standard concrete descendants of istream and ostream, you will already
|
105 |
|
|
know about them.
|
106 |
|
|
|
107 |
|
|
Finally, <iostream> provides the eight standard
|
108 |
|
|
global objects (cin, cout, etc). To do this correctly, this header
|
109 |
|
|
also provides the contents of the <istream> and <ostream>
|
110 |
|
|
headers, but nothing else. The contents of this header look like
|
111 |
|
|
|
112 |
|
|
|
113 |
|
|
#include <ostream>
|
114 |
|
|
#include <istream>
|
115 |
|
|
|
116 |
|
|
namespace std
|
117 |
|
|
{
|
118 |
|
|
extern istream cin;
|
119 |
|
|
extern ostream cout;
|
120 |
|
|
....
|
121 |
|
|
|
122 |
|
|
// this is explained below
|
123 |
|
|
static ios_base::Init __foo; // not its real name
|
124 |
|
|
}
|
125 |
|
|
|
126 |
|
|
Now, the runtime penalty mentioned previously: the global objects
|
127 |
|
|
must be initialized before any of your own code uses them; this is
|
128 |
|
|
guaranteed by the standard. Like any other global object, they must
|
129 |
|
|
be initialized once and only once. This is typically done with a
|
130 |
|
|
construct like the one above, and the nested class ios_base::Init is
|
131 |
|
|
specified in the standard for just this reason.
|
132 |
|
|
|
133 |
|
|
How does it work? Because the header is included before any of your
|
134 |
|
|
code, the __foo object is constructed before any of
|
135 |
|
|
your objects. (Global objects are built in the order in which they
|
136 |
|
|
are declared, and destroyed in reverse order.) The first time the
|
137 |
|
|
constructor runs, the eight stream objects are set up.
|
138 |
|
|
|
139 |
|
|
The static keyword means that each object file compiled
|
140 |
|
|
from a source file containing <iostream> will have its own
|
141 |
|
|
private copy of __foo. There is no specified order
|
142 |
|
|
of construction across object files (it's one of those pesky NP
|
143 |
|
|
problems that make life so interesting), so one copy in each object
|
144 |
|
|
file means that the stream objects are guaranteed to be set up before
|
145 |
|
|
any of your code which uses them could run, thereby meeting the
|
146 |
|
|
requirements of the standard.
|
147 |
|
|
|
148 |
|
|
The penalty, of course, is that after the first copy of
|
149 |
|
|
__foo is constructed, all the others are just wasted
|
150 |
|
|
processor time. The time spent is merely for an increment-and-test
|
151 |
|
|
inside a function call, but over several dozen or hundreds of object
|
152 |
|
|
files, that time can add up. (It's not in a tight loop, either.)
|
153 |
|
|
|
154 |
|
|
The lesson? Only include <iostream> when you need to use one of
|
155 |
|
|
the standard objects in that source file; you'll pay less startup
|
156 |
|
|
time. Only include the header files you need to in general; your
|
157 |
|
|
compile times will go down when there's less parsing work to do.
|
158 |
|
|
|
159 |
|
|
|
160 |
|
|
|
161 |
|
|
|
162 |
|
|
|
163 |
|
|
|
164 |
|
|
|
165 |
|
|
Stream Buffers
|
166 |
|
|
|
167 |
|
|
|
168 |
|
|
Derived streambuf Classes
|
169 |
|
|
|
170 |
|
|
|
171 |
|
|
|
172 |
|
|
Creating your own stream buffers for I/O can be remarkably easy.
|
173 |
|
|
If you are interested in doing so, we highly recommend two very
|
174 |
|
|
excellent books:
|
175 |
|
|
Standard C++
|
176 |
|
|
IOStreams and Locales by Langer and Kreft, ISBN 0-201-18395-1, and
|
177 |
|
|
The C++ Standard Library
|
178 |
|
|
by Nicolai Josuttis, ISBN 0-201-37926-0. Both are published by
|
179 |
|
|
Addison-Wesley, who isn't paying us a cent for saying that, honest.
|
180 |
|
|
|
181 |
|
|
Here is a simple example, io/outbuf1, from the Josuttis text. It
|
182 |
|
|
transforms everything sent through it to uppercase. This version
|
183 |
|
|
assumes many things about the nature of the character type being
|
184 |
|
|
used (for more information, read the books or the newsgroups):
|
185 |
|
|
|
186 |
|
|
|
187 |
|
|
#include <iostream>
|
188 |
|
|
#include <streambuf>
|
189 |
|
|
#include <locale>
|
190 |
|
|
#include <cstdio>
|
191 |
|
|
|
192 |
|
|
class outbuf : public std::streambuf
|
193 |
|
|
{
|
194 |
|
|
protected:
|
195 |
|
|
/* central output function
|
196 |
|
|
* - print characters in uppercase mode
|
197 |
|
|
*/
|
198 |
|
|
virtual int_type overflow (int_type c) {
|
199 |
|
|
if (c != EOF) {
|
200 |
|
|
// convert lowercase to uppercase
|
201 |
|
|
c = std::toupper(static_cast<char>(c),getloc());
|
202 |
|
|
|
203 |
|
|
// and write the character to the standard output
|
204 |
|
|
if (putchar(c) == EOF) {
|
205 |
|
|
return EOF;
|
206 |
|
|
}
|
207 |
|
|
}
|
208 |
|
|
return c;
|
209 |
|
|
}
|
210 |
|
|
};
|
211 |
|
|
|
212 |
|
|
int main()
|
213 |
|
|
{
|
214 |
|
|
// create special output buffer
|
215 |
|
|
outbuf ob;
|
216 |
|
|
// initialize output stream with that output buffer
|
217 |
|
|
std::ostream out(&ob);
|
218 |
|
|
|
219 |
|
|
out << "31 hexadecimal: "
|
220 |
|
|
<< std::hex << 31 << std::endl;
|
221 |
|
|
return 0;
|
222 |
|
|
}
|
223 |
|
|
|
224 |
|
|
Try it yourself! More examples can be found in 3.1.x code, in
|
225 |
|
|
include/ext/*_filebuf.h , and in this article by James Kanze:
|
226 |
|
|
Filtering
|
227 |
|
|
Streambufs.
|
228 |
|
|
|
229 |
|
|
|
230 |
|
|
|
231 |
|
|
|
232 |
|
|
|
233 |
|
|
Buffering
|
234 |
|
|
First, are you sure that you understand buffering? Chaptericularly
|
235 |
|
|
the fact that C++ may not, in fact, have anything to do with it?
|
236 |
|
|
|
237 |
|
|
The rules for buffering can be a little odd, but they aren't any
|
238 |
|
|
different from those of C. (Maybe that's why they can be a bit
|
239 |
|
|
odd.) Many people think that writing a newline to an output
|
240 |
|
|
stream automatically flushes the output buffer. This is true only
|
241 |
|
|
when the output stream is, in fact, a terminal and not a file
|
242 |
|
|
or some other device -- and that may not even be true
|
243 |
|
|
since C++ says nothing about files nor terminals. All of that is
|
244 |
|
|
system-dependent. (The "newline-buffer-flushing only occurring
|
245 |
|
|
on terminals" thing is mostly true on Unix systems, though.)
|
246 |
|
|
|
247 |
|
|
Some people also believe that sending endl down an
|
248 |
|
|
output stream only writes a newline. This is incorrect; after a
|
249 |
|
|
newline is written, the buffer is also flushed. Perhaps this
|
250 |
|
|
is the effect you want when writing to a screen -- get the text
|
251 |
|
|
out as soon as possible, etc -- but the buffering is largely
|
252 |
|
|
wasted when doing this to a file:
|
253 |
|
|
|
254 |
|
|
|
255 |
|
|
output << "a line of text" << endl;
|
256 |
|
|
output << some_data_variable << endl;
|
257 |
|
|
output << "another line of text" << endl;
|
258 |
|
|
The proper thing to do in this case to just write the data out
|
259 |
|
|
and let the libraries and the system worry about the buffering.
|
260 |
|
|
If you need a newline, just write a newline:
|
261 |
|
|
|
262 |
|
|
|
263 |
|
|
output << "a line of text\n"
|
264 |
|
|
<< some_data_variable << '\n'
|
265 |
|
|
<< "another line of text\n";
|
266 |
|
|
I have also joined the output statements into a single statement.
|
267 |
|
|
You could make the code prettier by moving the single newline to
|
268 |
|
|
the start of the quoted text on the last line, for example.
|
269 |
|
|
|
270 |
|
|
If you do need to flush the buffer above, you can send an
|
271 |
|
|
endl if you also need a newline, or just flush the buffer
|
272 |
|
|
yourself:
|
273 |
|
|
|
274 |
|
|
|
275 |
|
|
output << ...... << flush; // can use std::flush manipulator
|
276 |
|
|
output.flush(); // or call a member fn
|
277 |
|
|
On the other hand, there are times when writing to a file should
|
278 |
|
|
be like writing to standard error; no buffering should be done
|
279 |
|
|
because the data needs to appear quickly (a prime example is a
|
280 |
|
|
log file for security-related information). The way to do this is
|
281 |
|
|
just to turn off the buffering before any I/O operations at
|
282 |
|
|
all have been done (note that opening counts as an I/O operation):
|
283 |
|
|
|
284 |
|
|
|
285 |
|
|
std::ofstream os;
|
286 |
|
|
std::ifstream is;
|
287 |
|
|
int i;
|
288 |
|
|
|
289 |
|
|
os.rdbuf()->pubsetbuf(0,0);
|
290 |
|
|
is.rdbuf()->pubsetbuf(0,0);
|
291 |
|
|
|
292 |
|
|
os.open("/foo/bar/baz");
|
293 |
|
|
is.open("/qux/quux/quuux");
|
294 |
|
|
...
|
295 |
|
|
os << "this data is written immediately\n";
|
296 |
|
|
is >> i; // and this will probably cause a disk read
|
297 |
|
|
Since all aspects of buffering are handled by a streambuf-derived
|
298 |
|
|
member, it is necessary to get at that member with rdbuf() .
|
299 |
|
|
Then the public version of setbuf can be called. The
|
300 |
|
|
arguments are the same as those for the Standard C I/O Library
|
301 |
|
|
function (a buffer area followed by its size).
|
302 |
|
|
|
303 |
|
|
A great deal of this is implementation-dependent. For example,
|
304 |
|
|
streambuf does not specify any actions for its own
|
305 |
|
|
setbuf() -ish functions; the classes derived from
|
306 |
|
|
streambuf each define behavior that "makes
|
307 |
|
|
sense" for that class: an argument of (0,0) turns off buffering
|
308 |
|
|
for filebuf but does nothing at all for its siblings
|
309 |
|
|
stringbuf and strstreambuf , and specifying
|
310 |
|
|
anything other than (0,0) has varying effects.
|
311 |
|
|
User-defined classes derived from streambuf can
|
312 |
|
|
do whatever they want. (For filebuf and arguments for
|
313 |
|
|
(p,s) other than zeros, libstdc++ does what you'd expect:
|
314 |
|
|
the first s bytes of p are used as a buffer,
|
315 |
|
|
which you must allocate and deallocate.)
|
316 |
|
|
|
317 |
|
|
A last reminder: there are usually more buffers involved than
|
318 |
|
|
just those at the language/library level. Kernel buffers, disk
|
319 |
|
|
buffers, and the like will also have an effect. Inspecting and
|
320 |
|
|
changing those are system-dependent.
|
321 |
|
|
|
322 |
|
|
|
323 |
|
|
|
324 |
|
|
|
325 |
|
|
|
326 |
|
|
|
327 |
|
|
|
328 |
|
|
|
329 |
|
|
Memory Based Streams
|
330 |
|
|
|
331 |
|
|
Compatibility With strstream
|
332 |
|
|
|
333 |
|
|
|
334 |
|
|
Stringstreams (defined in the header <sstream> )
|
335 |
|
|
are in this author's opinion one of the coolest things since
|
336 |
|
|
sliced time. An example of their use is in the Received Wisdom
|
337 |
|
|
section for Sect1 21 (Strings),
|
338 |
|
|
describing how to
|
339 |
|
|
format strings.
|
340 |
|
|
|
341 |
|
|
The quick definition is: they are siblings of ifstream and ofstream,
|
342 |
|
|
and they do for std::string what their siblings do for
|
343 |
|
|
files. All that work you put into writing << and
|
344 |
|
|
>> functions for your classes now pays off
|
345 |
|
|
again! Need to format a string before passing the string
|
346 |
|
|
to a function? Send your stuff via << to an
|
347 |
|
|
ostringstream. You've read a string as input and need to parse it?
|
348 |
|
|
Initialize an istringstream with that string, and then pull pieces
|
349 |
|
|
out of it with >> . Have a stringstream and need to
|
350 |
|
|
get a copy of the string inside? Just call the str()
|
351 |
|
|
member function.
|
352 |
|
|
|
353 |
|
|
This only works if you've written your
|
354 |
|
|
<< />> functions correctly, though,
|
355 |
|
|
and correctly means that they take istreams and ostreams as
|
356 |
|
|
parameters, not ifstreams and ofstreams. If they
|
357 |
|
|
take the latter, then your I/O operators will work fine with
|
358 |
|
|
file streams, but with nothing else -- including stringstreams.
|
359 |
|
|
|
360 |
|
|
If you are a user of the strstream classes, you need to update
|
361 |
|
|
your code. You don't have to explicitly append ends to
|
362 |
|
|
terminate the C-style character array, you don't have to mess with
|
363 |
|
|
"freezing" functions, and you don't have to manage the
|
364 |
|
|
memory yourself. The strstreams have been officially deprecated,
|
365 |
|
|
which means that 1) future revisions of the C++ Standard won't
|
366 |
|
|
support them, and 2) if you use them, people will laugh at you.
|
367 |
|
|
|
368 |
|
|
|
369 |
|
|
|
370 |
|
|
|
371 |
|
|
|
372 |
|
|
|
373 |
|
|
|
374 |
|
|
|
375 |
|
|
|
376 |
|
|
File Based Streams
|
377 |
|
|
|
378 |
|
|
|
379 |
|
|
Copying a File
|
380 |
|
|
|
381 |
|
|
|
382 |
|
|
|
383 |
|
|
So you want to copy a file quickly and easily, and most important,
|
384 |
|
|
completely portably. And since this is C++, you have an open
|
385 |
|
|
ifstream (call it IN) and an open ofstream (call it OUT):
|
386 |
|
|
|
387 |
|
|
|
388 |
|
|
#include <fstream>
|
389 |
|
|
|
390 |
|
|
std::ifstream IN ("input_file");
|
391 |
|
|
std::ofstream OUT ("output_file");
|
392 |
|
|
Here's the easiest way to get it completely wrong:
|
393 |
|
|
|
394 |
|
|
|
395 |
|
|
OUT << IN;
|
396 |
|
|
For those of you who don't already know why this doesn't work
|
397 |
|
|
(probably from having done it before), I invite you to quickly
|
398 |
|
|
create a simple text file called "input_file" containing
|
399 |
|
|
the sentence
|
400 |
|
|
|
401 |
|
|
|
402 |
|
|
The quick brown fox jumped over the lazy dog.
|
403 |
|
|
surrounded by blank lines. Code it up and try it. The contents
|
404 |
|
|
of "output_file" may surprise you.
|
405 |
|
|
|
406 |
|
|
Seriously, go do it. Get surprised, then come back. It's worth it.
|
407 |
|
|
|
408 |
|
|
The thing to remember is that the basic_[io]stream classes
|
409 |
|
|
handle formatting, nothing else. In chaptericular, they break up on
|
410 |
|
|
whitespace. The actual reading, writing, and storing of data is
|
411 |
|
|
handled by the basic_streambuf family. Fortunately, the
|
412 |
|
|
operator<< is overloaded to take an ostream and
|
413 |
|
|
a pointer-to-streambuf, in order to help with just this kind of
|
414 |
|
|
"dump the data verbatim" situation.
|
415 |
|
|
|
416 |
|
|
Why a pointer to streambuf and not just a streambuf? Well,
|
417 |
|
|
the [io]streams hold pointers (or references, depending on the
|
418 |
|
|
implementation) to their buffers, not the actual
|
419 |
|
|
buffers. This allows polymorphic behavior on the chapter of the buffers
|
420 |
|
|
as well as the streams themselves. The pointer is easily retrieved
|
421 |
|
|
using the rdbuf() member function. Therefore, the easiest
|
422 |
|
|
way to copy the file is:
|
423 |
|
|
|
424 |
|
|
|
425 |
|
|
OUT << IN.rdbuf();
|
426 |
|
|
So what was happening with OUT<<IN? Undefined
|
427 |
|
|
behavior, since that chaptericular << isn't defined by the Standard.
|
428 |
|
|
I have seen instances where it is implemented, but the character
|
429 |
|
|
extraction process removes all the whitespace, leaving you with no
|
430 |
|
|
blank lines and only "Thequickbrownfox...". With
|
431 |
|
|
libraries that do not define that operator, IN (or one of IN's
|
432 |
|
|
member pointers) sometimes gets converted to a void*, and the output
|
433 |
|
|
file then contains a perfect text representation of a hexadecimal
|
434 |
|
|
address (quite a big surprise). Others don't compile at all.
|
435 |
|
|
|
436 |
|
|
Also note that none of this is specific to o*f*streams.
|
437 |
|
|
The operators shown above are all defined in the parent
|
438 |
|
|
basic_ostream class and are therefore available with all possible
|
439 |
|
|
descendants.
|
440 |
|
|
|
441 |
|
|
|
442 |
|
|
|
443 |
|
|
|
444 |
|
|
|
445 |
|
|
Binary Input and Output
|
446 |
|
|
|
447 |
|
|
|
448 |
|
|
The first and most important thing to remember about binary I/O is
|
449 |
|
|
that opening a file with ios::binary is not, repeat
|
450 |
|
|
not, the only thing you have to do. It is not a silver
|
451 |
|
|
bullet, and will not allow you to use the <</>>
|
452 |
|
|
operators of the normal fstreams to do binary I/O.
|
453 |
|
|
|
454 |
|
|
Sorry. Them's the breaks.
|
455 |
|
|
|
456 |
|
|
This isn't going to try and be a complete tutorial on reading and
|
457 |
|
|
writing binary files (because "binary"
|
458 |
|
|
covers a lot of ground), but we will try and clear
|
459 |
|
|
up a couple of misconceptions and common errors.
|
460 |
|
|
|
461 |
|
|
First, ios::binary has exactly one defined effect, no more
|
462 |
|
|
and no less. Normal text mode has to be concerned with the newline
|
463 |
|
|
characters, and the runtime system will translate between (for
|
464 |
|
|
example) '\n' and the appropriate end-of-line sequence (LF on Unix,
|
465 |
|
|
CRLF on DOS, CR on Macintosh, etc). (There are other things that
|
466 |
|
|
normal mode does, but that's the most obvious.) Opening a file in
|
467 |
|
|
binary mode disables this conversion, so reading a CRLF sequence
|
468 |
|
|
under Windows won't accidentally get mapped to a '\n' character, etc.
|
469 |
|
|
Binary mode is not supposed to suddenly give you a bitstream, and
|
470 |
|
|
if it is doing so in your program then you've discovered a bug in
|
471 |
|
|
your vendor's compiler (or some other chapter of the C++ implementation,
|
472 |
|
|
possibly the runtime system).
|
473 |
|
|
|
474 |
|
|
Second, using << to write and >> to
|
475 |
|
|
read isn't going to work with the standard file stream classes, even
|
476 |
|
|
if you use skipws during reading. Why not? Because
|
477 |
|
|
ifstream and ofstream exist for the purpose of formatting,
|
478 |
|
|
not reading and writing. Their job is to interpret the data into
|
479 |
|
|
text characters, and that's exactly what you don't want to happen
|
480 |
|
|
during binary I/O.
|
481 |
|
|
|
482 |
|
|
Third, using the get() and put()/write() member
|
483 |
|
|
functions still aren't guaranteed to help you. These are
|
484 |
|
|
"unformatted" I/O functions, but still character-based.
|
485 |
|
|
(This may or may not be what you want, see below.)
|
486 |
|
|
|
487 |
|
|
Notice how all the problems here are due to the inappropriate use
|
488 |
|
|
of formatting functions and classes to perform something
|
489 |
|
|
which requires that formatting not be done? There are a
|
490 |
|
|
seemingly infinite number of solutions, and a few are listed here:
|
491 |
|
|
|
492 |
|
|
|
493 |
|
|
|
494 |
|
|
Derive your own fstream-type classes and write your own
|
495 |
|
|
<</>> operators to do binary I/O on whatever data
|
496 |
|
|
types you're using.
|
497 |
|
|
|
498 |
|
|
|
499 |
|
|
This is a Bad Thing, because while
|
500 |
|
|
the compiler would probably be just fine with it, other humans
|
501 |
|
|
are going to be confused. The overloaded bitshift operators
|
502 |
|
|
have a well-defined meaning (formatting), and this breaks it.
|
503 |
|
|
|
504 |
|
|
|
505 |
|
|
|
506 |
|
|
|
507 |
|
|
Build the file structure in memory, then
|
508 |
|
|
mmap() the file and copy the
|
509 |
|
|
structure.
|
510 |
|
|
|
511 |
|
|
|
512 |
|
|
|
513 |
|
|
Well, this is easy to make work, and easy to break, and is
|
514 |
|
|
pretty equivalent to using ::read() and
|
515 |
|
|
::write() directly, and makes no use of the
|
516 |
|
|
iostream library at all...
|
517 |
|
|
|
518 |
|
|
|
519 |
|
|
|
520 |
|
|
|
521 |
|
|
Use streambufs, that's what they're there for.
|
522 |
|
|
|
523 |
|
|
|
524 |
|
|
While not trivial for the beginner, this is the best of all
|
525 |
|
|
solutions. The streambuf/filebuf layer is the layer that is
|
526 |
|
|
responsible for actual I/O. If you want to use the C++
|
527 |
|
|
library for binary I/O, this is where you start.
|
528 |
|
|
|
529 |
|
|
|
530 |
|
|
|
531 |
|
|
How to go about using streambufs is a bit beyond the scope of this
|
532 |
|
|
document (at least for now), but while streambufs go a long way,
|
533 |
|
|
they still leave a couple of things up to you, the programmer.
|
534 |
|
|
As an example, byte ordering is completely between you and the
|
535 |
|
|
operating system, and you have to handle it yourself.
|
536 |
|
|
|
537 |
|
|
Deriving a streambuf or filebuf
|
538 |
|
|
class from the standard ones, one that is specific to your data
|
539 |
|
|
types (or an abstraction thereof) is probably a good idea, and
|
540 |
|
|
lots of examples exist in journals and on Usenet. Using the
|
541 |
|
|
standard filebufs directly (either by declaring your own or by
|
542 |
|
|
using the pointer returned from an fstream's rdbuf() )
|
543 |
|
|
is certainly feasible as well.
|
544 |
|
|
|
545 |
|
|
One area that causes problems is trying to do bit-by-bit operations
|
546 |
|
|
with filebufs. C++ is no different from C in this respect: I/O
|
547 |
|
|
must be done at the byte level. If you're trying to read or write
|
548 |
|
|
a few bits at a time, you're going about it the wrong way. You
|
549 |
|
|
must read/write an integral number of bytes and then process the
|
550 |
|
|
bytes. (For example, the streambuf functions take and return
|
551 |
|
|
variables of type int_type .)
|
552 |
|
|
|
553 |
|
|
Another area of problems is opening text files in binary mode.
|
554 |
|
|
Generally, binary mode is intended for binary files, and opening
|
555 |
|
|
text files in binary mode means that you now have to deal with all of
|
556 |
|
|
those end-of-line and end-of-file problems that we mentioned before.
|
557 |
|
|
|
558 |
|
|
|
559 |
|
|
An instructive thread from comp.lang.c++.moderated delved off into
|
560 |
|
|
this topic starting more or less at
|
561 |
|
|
this
|
562 |
|
|
post and continuing to the end of the thread. (The subject heading is "binary iostreams" on both comp.std.c++
|
563 |
|
|
and comp.lang.c++.moderated.) Take special note of the replies by James Kanze and Dietmar Kühl.
|
564 |
|
|
|
565 |
|
|
Briefly, the problems of byte ordering and type sizes mean that
|
566 |
|
|
the unformatted functions like ostream::put() and
|
567 |
|
|
istream::get() cannot safely be used to communicate
|
568 |
|
|
between arbitrary programs, or across a network, or from one
|
569 |
|
|
invocation of a program to another invocation of the same program
|
570 |
|
|
on a different platform, etc.
|
571 |
|
|
|
572 |
|
|
|
573 |
|
|
|
574 |
|
|
|
575 |
|
|
|
576 |
|
|
|
577 |
|
|
|
578 |
|
|
|
579 |
|
|
Interacting with C
|
580 |
|
|
|
581 |
|
|
|
582 |
|
|
|
583 |
|
|
Using FILE* and file descriptors
|
584 |
|
|
|
585 |
|
|
See the extensions for using
|
586 |
|
|
FILE and file descriptors with
|
587 |
|
|
ofstream and
|
588 |
|
|
ifstream.
|
589 |
|
|
|
590 |
|
|
|
591 |
|
|
|
592 |
|
|
|
593 |
|
|
Performance
|
594 |
|
|
|
595 |
|
|
Pathetic Performance? Ditch C.
|
596 |
|
|
|
597 |
|
|
It sounds like a flame on C, but it isn't. Really. Calm down.
|
598 |
|
|
I'm just saying it to get your attention.
|
599 |
|
|
|
600 |
|
|
Because the C++ library includes the C library, both C-style and
|
601 |
|
|
C++-style I/O have to work at the same time. For example:
|
602 |
|
|
|
603 |
|
|
|
604 |
|
|
#include <iostream>
|
605 |
|
|
#include <cstdio>
|
606 |
|
|
|
607 |
|
|
std::cout << "Hel";
|
608 |
|
|
std::printf ("lo, worl");
|
609 |
|
|
std::cout << "d!\n";
|
610 |
|
|
|
611 |
|
|
This must do what you think it does.
|
612 |
|
|
|
613 |
|
|
Alert members of the audience will immediately notice that buffering
|
614 |
|
|
is going to make a hash of the output unless special steps are taken.
|
615 |
|
|
|
616 |
|
|
The special steps taken by libstdc++, at least for version 3.0,
|
617 |
|
|
involve doing very little buffering for the standard streams, leaving
|
618 |
|
|
most of the buffering to the underlying C library. (This kind of
|
619 |
|
|
thing is tricky to get right.)
|
620 |
|
|
The upside is that correctness is ensured. The downside is that
|
621 |
|
|
writing through cout can quite easily lead to awful
|
622 |
|
|
performance when the C++ I/O library is layered on top of the C I/O
|
623 |
|
|
library (as it is for 3.0 by default). Some patches have been applied
|
624 |
|
|
which improve the situation for 3.1.
|
625 |
|
|
|
626 |
|
|
However, the C and C++ standard streams only need to be kept in sync
|
627 |
|
|
when both libraries' facilities are in use. If your program only uses
|
628 |
|
|
C++ I/O, then there's no need to sync with the C streams. The right
|
629 |
|
|
thing to do in this case is to call
|
630 |
|
|
|
631 |
|
|
|
632 |
|
|
#include any of the I/O headers such as ios, iostream, etc
|
633 |
|
|
|
634 |
|
|
std::ios::sync_with_stdio(false);
|
635 |
|
|
|
636 |
|
|
You must do this before performing any I/O via the C++ stream objects.
|
637 |
|
|
Once you call this, the C++ streams will operate independently of the
|
638 |
|
|
(unused) C streams. For GCC 3.x, this means that cout and
|
639 |
|
|
company will become fully buffered on their own.
|
640 |
|
|
|
641 |
|
|
Note, by the way, that the synchronization requirement only applies to
|
642 |
|
|
the standard streams (cin , cout ,
|
643 |
|
|
cerr ,
|
644 |
|
|
clog , and their wide-character counterchapters). File stream
|
645 |
|
|
objects that you declare yourself have no such requirement and are fully
|
646 |
|
|
buffered.
|
647 |
|
|
|
648 |
|
|
|
649 |
|
|
|
650 |
|
|
|
651 |
|
|
|
652 |
|
|
|
653 |
|
|
|