Tempfiles in unittests
Jonathan M Davis
jmdavisProg at gmx.com
Fri Mar 9 11:38:43 PST 2012
On Friday, March 09, 2012 11:34:07 H. S. Teoh wrote:
> On Fri, Mar 09, 2012 at 01:42:01PM -0500, Jonathan M Davis wrote:
> > On Friday, March 09, 2012 16:48:33 Magnus Lie Hetland wrote:
> > > On 2012-03-09 15:08:42 +0000, bearophile said:
> > > > Magnus Lie Hetland:
> > > >> It seems that File has no method for reading the entire file
> > > >> contents into a string, so I'd have to read and concatenate lines
> > > >> or chunks or something?
> > > >
> > > > There are std.file.read() and std.file.readText().
> > >
> > > Yeah, I found those. I guess my post was a bit verbose, but the main
> > > point was that I have a File object, but no file name (because I'm
> > > using std.stdio.tmpfile() in a unit test), so std.file.read() and
> > > std.file.readText() are useless to me... :)
> >
> > File has a name property. You can do something like
> >
> > auto file = File.tmpfile();
> > auto filename = file.name;
> > auto str = readText(filename);
> >
> > I do grant you though that it's a bit odd to need to get the file name
> > and operate on that rather than operating on the File object. It works
> > though, and is a lot cleaner than reading in the file line-by-line, if
> > you don't actually need to do that.
>
> [...]
>
> This seems like a strange limitation. Shouldn't it be possible to slurp
> the entire contents of an already-open file into a string? Perhaps a new
> method in File?
>
> Also, using file.name is prone to race conditions in certain situations.
> (Not that it'd be a problem usually, but just sayin'.)
Of course it's possible to read in the open file into a string. It's just that
the only function in Phobos for doing that is in std.file and does not operate
on a File. All of the File functions read in only a portion of the file. So,
either a new function would have to be added to File, or you'd have to write
one yourself (which wouldn't be all that hard using what's already there).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list