简体   繁体   English

Haskell的hGetContents不返回任何内容,即使我知道该文件包含文本

[英]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.

相关问题 Haskell中的参数hGetContents无效 - Invalid argument hGetContents in Haskell Haskell hGetContents错误 - Haskell hGetContents error 我需要创建一个文本文件,其中包含haskell中函数的输出 - i need to create a text file that contains the output of my function in haskell 为什么我不能在打印hGetContents的结果后使用hPutStr? - Why can't I use hPutStr after printing the result of hGetContents? 读取Haskell中具有“ US-ASCII”编码的文件:hGetContents:无效的参数(无效的字节序列) - Reading file with “US-ASCII” encoding in Haskell: hGetContents: invalid argument (invalid byte sequence) Haskell,即使我的类型未指定,我也会收到此错误:无法将类型“a”与“[a]”匹配,“a”是绑定的刚性类型变量 - Haskell, Even though my type is not specified I get this error: Couldn't match type `a' with `[a]', `a' is a rigid type variable bound by 我怎样才能让 Haskell 知道我不在乎泛型的类型是什么? - How can I let Haskell know I don't care what a generic's type is? 如果与`threadDelay`&gt; 1秒一起使用,Haskell的`putChar`将不会打印任何内容 - Haskell's `putChar` doesn't print anything if used with `threadDelay` > 1 sec Haskell hGetContents 不读取用外部程序写入的数据 - Haskell hGetContents not reading data written with external program Haskell,hGetContents 阻塞问题(阅读更多行) - Haskell, hGetContents blocking problem (reading more lines)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM