1

I have a small bit of code that isn't behaving as I expected it too:

tempTest = do
    (_,tHand) <- openTempFile "." "tempTest.txt"
    hPutStr tHand "Test!"
    read <- hGetContents tHand
    putStrLn read

It writes to the file correctly, but when asked to display the contents to the screen, it shows only a new line (without any quotes). Given how simple this is, I'm assuming I'm misunderstanding how getContents works. From what I understand, it reads the file in chunks instead of all at once; which prevents the memory from being filled up by a massive file being read. Why is "read' not receiving anything from hGetContents? Any help here would be appreciated.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • 1
    Note that similar problems often turn up with Haskell's standard IO routines because of _lazyness_. That was completely innocent in this case, but generally it's often a good idea to just go for completely strict IO, i.e. open & read an entire file and immediately close it: the time and memory needed is often neglectable (though sometimes it isn't of course!), and you get much simpler, reliable semantics. – leftaroundabout Jul 18 '14 at 18:38
  • I haven't knowingly used anything strict in Haskell yet. The only method I know of for ensuring strictness is the $! operator, which, as far as I know causes `seq` to be called during the application (so I guess I know of `seq` aswell). I have yet to use either though. – Carcigenicate Jul 18 '14 at 23:28

1 Answers1

9

The problem here is that the handle of your file points to the end of the file. This should work:

tempTest = do
    (_,tHand) <- openTempFile "." "tempTest.txt"
    hPutStr tHand "Test!"
    hSeek tHand AbsoluteSeek 0 -- move the file handle to beginning of file
    read <- hGetContents tHand
    putStrLn read

Demo:

λ> tempTest
Test!

Here using the hSeek function, you move the Handle to the beginning of the file. Also, I would suggest you to close the file handle using hClose function after your work is done.

Sibi
  • 47,472
  • 16
  • 95
  • 163