[英]Haskell's hGetContents isn't returning anything, even though I know the file contains text
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. 鉴于这很简单,我假设我误解了getContents的工作原理。 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. 为什么“读取”没有从hGetContents接收任何信息,这里的任何帮助将不胜感激。
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. 在这里使用hSeek
函数,将Handle
移动到文件的开头。 Also, I would suggest you to close the file handle using hClose
function after your work is done. 另外,我建议您在完成工作后使用hClose
函数关闭文件句柄。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.