[英]Clean language: append number in end of file, fwritei doesn't work
我正在尝试编写接收[String]
文件名的函数, String
文件目录名和*f
。 该函数将在每个文件的末尾附加一个整数。
这是我到目前为止所得到的:
import StdEnv
import StdFile
import FileManipulation
appendNumInEndOfVmFiles :: [String] String *f -> String
appendNumInEndOfVmFiles [] dirname w = "finished"
appendNumInEndOfVmFiles [x:xs] dirname w
# path = dirname +++ "\\\\" +++ x
# (ok,file,files) = fopen path FAppendText w
# file = fwritei 12 file
# (ok2,_) = fclose file w
= appendNumInEndOfVmFiles xs dirname w
Start w
// 1. Receive name of directory from the user.
# (io,w) = stdio w // open stdio
# io = fwrites "Enter name of directory:\n" io // ask for name
# (name,io) = freadline io // read in name
# name = name % (0, size name - 2) // remove \n from name
# (ok,w) = fclose io w // close stdio
| not ok = abort "Couldn't close stdio" // abort in case of failure
// 2. Get a list of all file names in that directory.
# (dir,w) = getDirectoryContents (RelativePath [PathDown name]) w
# fileList = getNamesOfFilesInDirectory (getEntriesList dir)
= appendNumInEndOfVmFiles (getVmFiles fileList) name w
假设getVmFiles
在我的定义FileManipulation.dcl
文件,并在这个问题的背景下name
是"myDir"
和文件列表["hello.vm","Wiki.vm"]
出于某种原因,即使我在屏幕上收到“完成”消息,文件也不会被修改。 无论我给fopen
什么样的整数,即使它的FWriteText
或FWriteData
它仍然什么都不做......即使我使用fwritec
或fwrites
字符也没有发生任何事情。
我在这里缺少什么? 非常感谢!
出于某种原因,即使我在屏幕上收到“完成”消息,文件也不会被修改。
这是由于懒惰的评估。 在appendNumInEndOfVmFiles
,不使用fclose
的结果,因此不评估fclose
。 因此,也不需要对fwritei
进行评估。 您可以通过在ok2
上添加防护来解决此ok2
:
# (ok2,_) = fclose file w
| not ok2 = abort "fclose failed\n"
= appendNumInEndOfVmFiles xs dirname w
但是,执行此操作的典型方法是重写函数以返回*f
而不是String
,以便此唯一值不会丢失。 只要使用结果,就会评估fwritei
。 您可以潜在地使*f
参数严格(即在前面添加一个!
)。 这将确保在进入函数之前对其进行评估,以便执行所有延迟文件关闭。
您的代码还有一些问题:
在这里, w
被使用了两次,这是非法的,因为它是严格类型。 您应该在守卫中使用(ok2,w)
以继续使用相同的环境。
# (ok2,_) = fclose file w = appendNumInEndOfVmFiles xs dirname w
appendNumInEndOfVmFiles
需要有一个类型上下文| FileSystem f
| FileSystem f
来解决fopen
和fclose
重载。
最后:
...即使它的
FWriteText
或FWriteData
...
只是让您知道:区别在于,第一个将以 ASCII 表示形式写入整数,而第二个将其二进制写入 4 或 8 个字节(取决于系统的位宽)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.