hSetFileSize takes a handle and an integer n as arguments and truncates the physical file with handle hdl to n bytes.
Prelude
System.IO> :t hSetFileSize
hSetFileSize
:: Handle -> Integer -> IO ()
Suppose
today.txt contains following data.
$ cat today.txt If you love a flower, don’t pick it up. Because if you pick it up it dies and it ceases to be what you love. So if you love a flower, let it be. Love is not about possession. Love is about appreciation.
Following
program truncate the file to half of the size.
FileUtil.hs
import System.IO main = do putStrLn "Enter file name (Including full path) to read" fileName <- getLine handle <- openFile fileName ReadWriteMode size <- hFileSize handle contents <- hGetContents handle putStrLn $ "Size is " ++ show size putStrLn $ "Content is : " ++ contents hClose handle handle1 <- openFile fileName ReadWriteMode hSetFileSize handle1 (size `div` 2) size1 <- hFileSize handle1 contents1 <- hGetContents handle1 putStrLn $ "Size is " ++ show size1 putStrLn $ "Content is : " ++ contents1 hClose handle1
$ ghc FileUtil.hs [1 of 1] Compiling Main ( FileUtil.hs, FileUtil.o ) Linking FileUtil ... $ $ $ ./FileUtil Enter file name (Including full path) to read today.txt Size is 206 Content is : If you love a flower, don’t pick it up. Because if you pick it up it dies and it ceases to be what you love. So if you love a flower, let it be. Love is not about possession. Love is about appreciation. Size is 103 Content is : If you love a flower, don’t pick it up. Because if you pick it up it dies and it ceases to be what yo $ $ cat today.txt If you love a flower, don’t pick it up. Because if you pick it up it dies and it ceases to be what yo
Previous Next Home
No comments:
Post a Comment