Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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.

I feel as if this error is strange in that the documentation for openFile states that

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.

touch :: FilePath -> IO ()
touch name = appendFile name ""
like image 439
Zylviij Avatar asked Aug 24 '26 11:08

Zylviij


1 Answers

Use touchFile from the unix package (System.Posix.Files.ByteString).


appendFile name "" does not work like touch; appendFile is a no-op when the string to append is empty.

You can confirm this by running stat on the file before and after and comparing the modification times.

like image 185
nh2 Avatar answered Aug 27 '26 03:08

nh2