
The 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 which (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 = do (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 . . .

Wed, 15 Nov 2000 18:42:29 +0100, George Russell
What I want instead is a function which (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.
Applying foldr (\_ t -> t) (return ()) to the string (and executing this application as an IO action) will force it to be read completely. If it came from readFile, the file gets closed as soon as the string is evaluated up to its end.
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 . . .
Unfortunately the design of these areas (conversion between Haskell strings and C strings) is not yet complete. And Unicode in Haskell strings (already implemented in GHC development versions) will make the library more complex. -- __("< Marcin Kowalczyk * qrczak@knm.org.pl http://qrczak.ids.net.pl/ \__/ ^^ SYGNATURA ZASTÊPCZA QRCZAK
participants (2)
-
George Russell
-
qrczak@knm.org.pl