Two little blog/tutorials posts.

Regan Heath regan at netwin.co.nz
Mon Feb 27 19:15:38 PST 2006


On Tue, 28 Feb 2006 10:40:47 +0800, Alan Knowles <alan at akbhome.com> wrote:
> I wrote these two, they may be of some interest...
>
>
> http://www.akbkhome.com/blog.php/View/114/interesting_languages__D.html
> http://www.akbkhome.com/blog.php/View/115/More_on_Digitalmars_D__Simple_SVG_render_for_GnomeCanvas.html
>
> I'm sure they are lacking in many ways, but feel free to post  
> comments/corrections ;)

Nice work! (but like Derek mentioned it doesn't look so good in Opera)

I'm mostly sure this is incorrect however (someone else correct me if I'm  
wrong)..

"
File f = new File( r"/tmp/data.svg", FileMode.In );
while (!f.eof()) {
   testdata ~= f.readString(  f.available());
}
almost as simple as file_get_contents(), and since D cleans up the File  
handle at the end of the method it's in, you dont really need to delete f  
to close the file handle."

D is garbage collected and the collector does not guarantee to call the  
destructor for the File object. So, the above code may never close the  
file.

However, D has a feature currently called 'auto' (I say 'currently'  
because there is some debate on the topic of late)

auto File f = new File( r"/tmp/data.svg", FileMode.In );
while (!f.eof()) {
   testdata ~= f.readString(  f.available());
}

'auto' will ensure the File object is deleted at the end of the scope.

Also, a recent new feature "on scope" can help here too:
   http://www.digitalmars.com/d/exception-safe.html
   http://www.digitalmars.com/d/statement.html#scope

Oh, and std.file contains a function "read" which will read an entire file  
into an array. It returns a void[] which can be cast to whatever array  
type you actually require, eg.

import std.file;
import std.stdio;

void main()
{
	wchar[] text = cast(wchar[])read("utf16.txt");
	writefln(text);
}

Regan



More information about the Digitalmars-d-learn mailing list