Reading and writing a class to a (binary) file
bearophile
bearophileHUGS at lycos.com
Mon Jan 7 10:08:06 PST 2013
Omid:
> As I am learning D as my first language, it may sound crazy.
D is one of the most complex languages, so your have to learn a
LOT. Learning about static typing is important, but usually as
first language I suggest Python, despite Python is not perfect.
> But I would appreciate if somebody tell me how to read and
> write a class (say with two objects, an integer an a char[20])
> to a file (text or binary).
This uses a text file. There are various ways to improve this
code.
import std.string: format;
import std.stdio: File, writeln;
import std.conv: to;
final class Foo {
private immutable int x;
private immutable char[20] txt;
this(in int x_, in string txt_) pure nothrow {
this.x = x_;
this.txt[0 .. txt_.length] = txt_;
this.txt[txt_.length .. $] = ' ';
}
override string toString() const {
return format("%d %s", x, txt);
}
void toFile(File fout) const {
fout.writef("%x %s\n", x, txt);
}
static Foo fromFile(File fin) {
int xx;
string s;
fin.readf("%x %s\n", &xx, &s);
return new Foo(xx, s);
}
}
void main() {
immutable fileName = "foo_test.txt";
auto fin = File(fileName, "wt");
(new Foo(10, "First test")).toFile(fin);
(new Foo(20, "Second test")).toFile(fin);
fin.close();
auto fout = File(fileName, "rt");
writeln(Foo.fromFile(fout));
writeln(Foo.fromFile(fout));
fout.close();
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list