Instant readFile

George Russell ger@Informatik.Uni-Bremen.DE
Wed, 15 Nov 2000 18:42:29 +0100

   readFile :: FilePath -> IO String
action returns the contents of the associated file.  This is almost what
I want, but not quite, because readFile is lazy.  Hence if the string is
only partly read, the file is still open.  What I want instead is a function
   (a) opens the file;
   (b) slurps the complete contents compactly into an array;
   (c) closes the file;
   (d) makes the contents of the array available as a String.
So instead I wrote the following:

copyFileToString  :: FilePath -> IO String
copyFileToString file =
      (addr,len) <- IOExts.slurpFile file
      CString.unpackCStringLenIO addr len

However on further consideration this also seems to me to be unsatisfactory, 
because although I don't understand this issue very well, I don't think
the (addr) address containing the complete file contents will ever get
deallocated, because there's no way the GC can know that this particular
Addr can be free'd.  (Is that correct?)  So please, how _should_ I write this
function?   For example, I could try and wrap the addr into a ForeignObj,
but then how would I ensure that when the String gets gc'd, the ForeignObj
does too?

It all is a bit of a mystery to me how you are supposed to use Addr like things
without space leaks.  A little more explanation in the documentation would not
perhaps be amiss . . .