text and binary data in same file

Started by
2 comments, last by Zahlman 14 years, 10 months ago
I'm trying to design a file that has a block of header information followed by a block of binary data, writing it is easy but I'm not sure how to read it correctly. The file would be arranged like so: [header size in bytes] [number of symbols in header] [first symbol] [corresponding data block] [next symbol] [corresponding data block]...[last symbol] [last data block] [end of header] [binary data] Can I read from a file in text mode then switch to binary mode without closing and re-opening the file ? If I can't do that, what would be the proper way to get the size of the header and then start reading binary data after that point ?
Advertisement
open it as binary and read the text part into a string (or strings), or an array of bytes, then read the rest of the data as required.
[size="2"]I like the Walrus best.
It sounds like all you need the text mode for is reading the header size. In which case, you can just read/write that as binary as well.
The only difference (that i am aware of) between the two modes is that text mode will read each line up to a newline char which is system dependant (i.e. \n on Unix bases systems, \r\n on Windows). But since you are storing blocks of data then that is not a concern.
[Window Detective] - Windows UI spy utility for programmers
"Text mode" versus "binary mode" for opening the file is a totally separate concept from "text I/O" (really "formatted" I/O) versus "binary I/O" (really "raw" I/O). It is perfectly OK to use operator>> on a stream opened with ios::binary set, or .read() on a stream opened without ios::binary set.

Files opened with ios::binary set are always "raw" in the sense that no linefeed translation will be done and no particular byte value will be interpreted as end-of-file. However, this does not appear to be a concern for you.

If there is whitespace between "first symbol" (which I'm assuming is a "word" of text) and "corresponding data block", you will want to consume that from the stream (with stream >> std::ws) before reading the block. Also, you'll need to know the size of the block somehow. :)

In general, it's usually easier to just use raw representations of the numbers in question, and four-character codes instead of your "symbols" to identify blocks.

This topic is closed to new replies.

Advertisement