r/w binary
Ali Çehreli
acehreli at yahoo.com
Thu Jun 30 00:53:02 PDT 2011
On Thu, 30 Jun 2011 15:52:59 +1200, Joel Christensen wrote:
> I'm thinking more about handling binary files. With the C version I
> would write a int for how many letters in the string, then put in the
> the string along side ([0005][house]). That way I can have any character
> at all (though I just thinking of char's).
I would still use a portable text format myself.
For binary, you should consider rawWrite() and rawRead(). Here is just a
start:
import std.stdio;
void main()
{
int i = 42;
auto file = File("deleteme.bin", "w");
file.rawWrite((&i)[0..1]);
}
(Aside: The 'b' for binary mode does nothing in POSIX systems; so it's
not necessary.)
The parameter to rawWrite() above is a nice feature of D: slicing a raw
pointer produces a safe slice:
http://digitalmars.com/d/2.0/arrays.html
<quote>
Slicing is not only handy for referring to parts of other arrays, but for
converting pointers into bounds-checked arrays:
int* p;
int[] b = p[0..8];
</quote>
For strings (actually arrays), you would need .length and .ptr properties.
I've never used it but you might want to consider the serialization
library Orange as well:
http://www.dsource.org/projects/orange
Ali
More information about the Digitalmars-d-learn
mailing list