“资源繁忙(文件被锁定)" Haskell中的错误 [英] "resource busy (file is locked)" error in Haskell

查看:129
本文介绍了“资源繁忙(文件被锁定)" Haskell中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Haskell非常陌生.实际上,我正在通过本教程的这一部分进行. 我碰到了这段代码:

I'm very new to Haskell. In fact, I'm working through this section of this tutorial. I came across this piece of code:

import System.IO     
import Data.Char  

main = do     
    contents <- readFile "girlfriend.txt"     
    writeFile "girlfriendcaps.txt" (map toUpper contents) 

哪个会读取名为"girlfriend.txt"的文件的内容,并将该文件的大写形式写入名为"girlfriendcaps.txt"的新文件中.

Which reads the contents of the file called "girlfriend.txt" and writes the upper-cased version of the file to a new file called "girlfriendcaps.txt".

因此,我想稍微修改一下代码以采用要操作的文件名.我将代码更改为此:

So, I wanted to modify the code a bit to take the name of the file to act on. I changed the code to this:

import System.IO
import Data.Char

main = do
    path <- getLine
    contents <- readFile path
    writeFile path (map toUpper contents)

现在,很明显,这里的主要区别是我正在读取和写入同一文件.正如我现在正在考虑的那样,这肯定是一个懒惰的评估,但是我收到了资源繁忙"的错误消息.如果我错了,请纠正我,但我猜想readFile直到writeFile要求提供文件内容才开始读取文件.然后writeFile尝试写入文件,但它仍必须打开文件,因为它也在询问内容.我靠近那里吗?

now, obviously the major difference here is that I'm reading from and writing to the same file. As I'm thinking about it now, this must be a lazy-evaluation thing, but i'm getting the "resource busy" error message. Correct me if I'm wrong, but I guess that readFile doesn't start reading the file until writeFile asks for the contents of it. And then writeFile tries to write to the file, but it must still have the file open because it's also asking for the contents. Am I close there?

所以,真正的问题是:如何在Haskell中读取和写入同一文件?这样做更有意义,因为您将经常从读取的文件中写入另一个文件,但是从我自己的观点出发,您将如何读取和写入相同的文件?

So, the real question is: how do I read from and write to the same file in Haskell? It makes sense that it's more difficult, because you will write to a different file from the file you read from more often than not, but for my own edification, how would you read and write to the same file?

推荐答案

完全取决于您要执行的操作.通常,在任何语言中,这都可能是一个糟糕的设计,因为如果程序内部或外部出现任何错误(例如,用户错误),则说明您已破坏了原始数据,无法重试.它还要求将整个文件保存在内存中,如果只有几个字节,这是很酷的,但是当有人决定在一个非常大的文件上运行它时,效果就不太好了.

Depends on exactly what you are trying to do. As a rule, in any language, this is probably a bad design because if anything goes wrong either inside the program or outside (e.g user error) then you have destroyed your original data and cannot try again. It also requires that the entire file be held in memory, which is cool if its just a few bytes, but not so good when someone decides to run this on a really big file.

如果您确实要执行此操作,则为输出生成一个临时文件名,然后,一旦知道您已成功写入该文件名,就可以删除原始文件并重命名新文件.

If you really want to do this then generate a temporary filename for the output, and then once you know that you have written to it successfully you can delete the original and rename the new one.

这篇关于“资源繁忙(文件被锁定)" Haskell中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆