简体   繁体   English

Haskell 实现Unix“touch”命令

[英]Haskell Implement Unix "touch" command

I'm trying to implement the touch command from the unix command line, but it seems that my last line throws an exception: ** Exception: ~/.todo: openFile: does not exist (No such file or directory)我正在尝试从 unix 命令行实现touch命令,但似乎我的最后一行抛出异常: ** Exception: ~/.todo: openFile: does not exist (No such file or directory)

main = touch "~/.todo"

touch :: FilePath -> IO ()
touch name = do
  exists <- doesFileExist name
  unless exists $ appendFile name ""

If there is any OS specific behavior, I'm testing from macOS Sierra.如果有任何特定于操作系统的行为,我正在从 macOS Sierra 进行测试。

I feel as if this error is strange in that the documentation for openFile states that我觉得这个错误很奇怪,因为openFile的文档指出

If the file does not exist and it is opened for output, it should be created as a new file.如果该文件不存在并且已打开输出,则应将其创建为新文件。

Any suggestions as to how to fix this?有关如何解决此问题的任何建议?

Edit: According to @chi, the touch command should always open the file, even if it already exists, because it will then update the file's last modified date.编辑:根据@chi, touch命令应该始终打开文件,即使它已经存在,因为它会更新文件的上次修改日期。

touch :: FilePath -> IO ()
touch name = appendFile name ""

Use touchFile from the unix package ( System.Posix.Files.ByteString ).使用unix包中的touchFile ( System.Posix.Files.ByteString )。


appendFile name "" does not work like touch ; appendFile name ""不像touch那样工作; appendFile is a no-op when the string to append is empty.当要追加的字符串为空时, appendFile是空操作。

You can confirm this by running stat on the file before and after and comparing the modification times.您可以通过在文件前后运行stat并比较修改时间来确认这一点。

In the future please paste all the code you are using that creates the error.将来,请粘贴您正在使用的所有会导致错误的代码。 This includes both the imports and the invocation.这包括导入和调用。 In your case it seems you are running something with a shell expansion character:在您的情况下,您似乎正在运行带有外壳扩展字符的东西:

*Main> touch "~/foobar"
*** Exception: ~/foobar: openFile: does not exist (No such file or directory)

The ~ is typically expanded by a shell (there also exists a C library that can do that rewriting for you). ~通常由 shell 扩展(还有一个 C 库可以为您进行重写)。 Most languages actually interpret that as a literal part of the path... but the ~ directory probably doesn't exist or that symbol might not even be valid depending on your platform.大多数语言实际上将其解释为路径的文字部分……但~目录可能不存在,或者该符号甚至可能无效,具体取决于您的平台。

Instead try a valid file path:而是尝试一个有效的文件路径:

*Main> touch "/tmp/thisfile"
*Main>
Leaving GHCi.
% ls -l /tmp/thisfile
-rw-rw-r--. 1 theuser theuser 0 Feb  3 12:51 /tmp/thisfile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM