开发者

openFile - permission denied - when reading and writing to the same file

开发者 https://www.devze.com 2023-03-07 23:22 出处:网络
I have an error \'openFile - permission denied\' when I try write something to file: saveFile content path = do

I have an error 'openFile - permission denied' when I try write something to file:

saveFile content path = do
 开发者_运维问答       writeFile path (show content)

why ?


From your questions, it appears that you're using readFile and writeFile from System.IO on the same file.

Remember that System.IO.readFile is lazy, meaning that the file handle is opened, initially, and then as your program requires data, pieces will be read. Only once all data has been read, or all references to the file dropped, will the file handle be closed. Until then the resource is locked.

You need to ensure the file is read fully before trying to write to it, or otherwise closed the file in some way. A simple way to achieve this is to use strict IO. E.g,:

loadFileStrict :: Read a => FilePath -> IO a
loadFileStrict f = do
    s <- readFile f
    length s `seq` return s

Here, we ask for the length of the string, before returning the result. This forces the entire contents to be read.

This pattern is captured in the strict package.

0

精彩评论

暂无评论...
验证码 换一张
取 消