我需要读取,修改并更新相同功能中的某些文件。理想的解决方案(见下文)无法工作,这是错误的。 “最差”解决方案有效。最短的代码来读取文件,然后更新它?
-- Ex. "Pseudocode" - Doesn't work.
ideal = let pathFile = "C:\\TEMP\\Foo.txt"
in readFile pathFile >>= writeFile pathFile . (++ "!")
-- It works.
worst = do
let pathFile = "C:\\TEMP\\Foo.txt"
h <- openFile pathFile ReadMode
cs <- hGetContents h
(temp_Foo,temp_handle) <- openTempFile pathFile
hPrint temp_handle $ cs ++ "!"
hClose temp_handle
removeFile pathFile
renameFile temp_Foo pathFile
我希望避免2010年“简单而丑陋的解决方法”,由里德·波顿建议:
doit file = do
contents <- readFile file
length contents `seq` (writeFile file $ process contents)
有没有更好的解决办法?
那么,你可以有一个管道/管道解决方案。 :) – Sibi
@Sibi这些库很大。我认为这需要很长时间才能掌握。另外,我不认为用大炮杀死蚊子。 –
@AlbertoCapitani你不需要大炮来杀死蚊子 - 但是你也不需要超级计算机(按70年代的标准)拨打电话。 – leftaroundabout