我正在嘗試打開一個檔案并將第一行移到最后,如下所示:
-- Moves the first line in a file to the end of the file (first line becomes last line)
flyttLn :: FilePath -> IO ()
flyttLn fn = do
fh <- openFile fn ReadMode
content <- hGetContents fh
--putStrLn content
let
(l1:rest) = lines content
newContent = unlines (rest [l1])
hClose fh
fh2 <- openFile fn WriteMode
hPutStr fh2 newContent
hClose fh2
由于懶惰的評估,這給了我一個錯誤。所以基于這個問題,我首先嘗試列印檔案的內容,然后重新撰寫它們。哪個有效,除了我不想在終端中列印整個檔案。所以我試著System.IO.Strict像這樣匯入
import qualified System.IO.Strict as SIO
但是 VS Code 給了我一個錯誤說
Could not find module ‘System.IO.Strict’
It is not a module in the current program, or in any known package.not found
我試圖找到類似的問題,但我只找到了這個問題,并沒有幫助我解決我的問題。
如何正確打開檔案并編輯其內容,而不必在終端中列印整個檔案?如何正確匯入 System.IO.Strict?
uj5u.com熱心網友回復:
該模塊System.IO.Strict在strict包中定義(我使用 hoogle找到了這個)。
我建議自己制作一個 cabal 或 stack 包并添加strict到依賴項中。對于 cabal,我會推薦官方入門指南。對于堆疊,您可以查看官方指南。
編輯:這個答案的第二部分是不正確的,因為你會得到相同的懶惰IO問題readFile不前完成writeFile。
uj5u.com熱心網友回復:
我不必System.IO.Strict用這個匯入:
flyttLn :: FilePath -> IO ()
flyttLn file =
do
fh <- openFile file ReadMode
content <- hGetContents fh
let
(l1:rest) = lines content
newContent = unlines (rest [l1])
(fn2, fh2) <- openTempFile "." "temp"
hPutStr fh2 newContent
hClose fh
hClose fh2
removeFile file
renameFile fn2 file
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358931.html
