turtle icon indicating copy to clipboard operation
turtle copied to clipboard

Check if a file is empty.

Open GregorySchwartz opened this issue 8 years ago • 4 comments

isEmpty :: FilePath -> Bool

Replacing "[ -s diff.txt ]" in bash.

GregorySchwartz avatar Feb 10 '17 14:02 GregorySchwartz

So you can do this using a combination of fold, null, and input, like this:

import Prelude hiding (FilePath)
import Turtle

import qualified Control.Foldl.Text

isEmpty :: MonadIO io => FilePath -> io Bool
isEmpty path = fold (input path) Control.Foldl.Text.null

The main reason I suggest combining these three functions is to reduce API proliferation. Otherwise I'd need to create similar utilities for other Folds in the same module for consistency

Gabriella439 avatar Feb 13 '17 22:02 Gabriella439

Very useful trick, thanks. I guess to make the compiler happy it should be

isFileEmpty :: MonadIO io => FilePath -> io Bool
isFileEmpty path =
  fold (lineToText <$> input path) Control.Foldl.Text.null

PierreR avatar Feb 24 '17 17:02 PierreR

Actually, there may be a simpler solution, which is to use Control.Foldl.null instead of Control.Foldl.Text.null (in other words, to check if the file has 0 lines instead of checking that it has 0 characters)

Gabriella439 avatar Feb 24 '17 17:02 Gabriella439

Control.Foldl.null does seem to work nicely for me. Nice.

PierreR avatar Feb 24 '17 20:02 PierreR