Joey Hess
2010-10-09 22:49:12 UTC
The function below always returns "", rather than the file's contents.
_Real World Haskell_ touches on how laziness can make this problimatic,
without really giving a solution, other than throwing in a putStr to
force evaluation, which can't be done here. How can I make hGetContents
strict, to ensure the file contents are really read before it gets closed?
readFile' file = do
f <- openFile file ReadMode
-- locking will go here
s <- hGetContents f
hClose f
return s
Also, I noticed that opening a file and locking it involves a
very verbose seeming dance. (It's 2 lines of code in most other languages.)
Does this indicate that few people bother with file locking in Haskell
and so it still has these rough edges, or that there's a better way to do
it that I have not found yet?
openLocked file = do
handle <- openFile file ReadMode
lockfd <- handleToFd handle -- closes handle
waitToSetLock lockfd (ReadLock, AbsoluteSeek, 0, 0)
handle' <- fdToHandle lockfd
return handle'
_Real World Haskell_ touches on how laziness can make this problimatic,
without really giving a solution, other than throwing in a putStr to
force evaluation, which can't be done here. How can I make hGetContents
strict, to ensure the file contents are really read before it gets closed?
readFile' file = do
f <- openFile file ReadMode
-- locking will go here
s <- hGetContents f
hClose f
return s
Also, I noticed that opening a file and locking it involves a
very verbose seeming dance. (It's 2 lines of code in most other languages.)
Does this indicate that few people bother with file locking in Haskell
and so it still has these rough edges, or that there's a better way to do
it that I have not found yet?
openLocked file = do
handle <- openFile file ReadMode
lockfd <- handleToFd handle -- closes handle
waitToSetLock lockfd (ReadLock, AbsoluteSeek, 0, 0)
handle' <- fdToHandle lockfd
return handle'
--
see shy jo
see shy jo