欢迎访问宙启技术站
智能推送

使用Haskell编写一个简单的文件处理程序

发布时间:2023-12-10 03:18:08

下面是一个使用Haskell编写的简单文件处理程序的例子:

module Main where

import System.IO

-- 读取文件内容并打印
readFileContents :: FilePath -> IO ()
readFileContents path = do
  content <- readFile path
  putStrLn content

-- 将指定字符串写入文件
writeToFile :: FilePath -> String -> IO ()
writeToFile path content = do
  writeFile path content

-- 追加指定字符串到文件末尾
appendToFile :: FilePath -> String -> IO ()
appendToFile path content = do
  appendFile path content

-- 复制源文件到目标文件
copyFile :: FilePath -> FilePath -> IO ()
copyFile srcPath destPath = do
  srcContent <- readFile srcPath
  writeFile destPath srcContent

main :: IO ()
main = do
  putStrLn "Welcome to the file processor!"

  putStrLn "Enter the content to write to a file:"
  content <- getLine
  writeToFile "output.txt" content
  putStrLn "Content has been written to output.txt file."

  putStrLn "Enter the content to append to the file:"
  appendContent <- getLine
  appendToFile "output.txt" appendContent
  putStrLn "Content has been appended to output.txt file."

  putStrLn "Copying output.txt to output_copy.txt..."
  copyFile "output.txt" "output_copy.txt"
  putStrLn "File has been copied."

  putStrLn "Contents of output_copy.txt:"
  readFileContents "output_copy.txt"

这个程序中,我们定义了几个函数来进行文件处理。readFileContents 函数接受一个文件路径作为参数,将文件内容读取出来并打印到控制台。writeToFile 函数接受一个文件路径和一个字符串作为参数,将字符串写入文件。appendToFile 函数和 writeToFile 函数类似,不同的是它会将内容追加到文件末尾而不是覆盖原有内容。copyFile 函数接受源文件路径和目标文件路径作为参数,将源文件的内容复制到目标文件。

main 函数中,我们首先打印欢迎信息,然后使用 writeToFile 函数将用户输入的内容写入文件 "output.txt",然后使用 appendToFile 函数将用户输入的内容追加到同一文件。接下来,我们使用 copyFile 函数复制 "output.txt" 文件到 "output_copy.txt"。最后,我们使用 readFileContents 函数读取 "output_copy.txt" 文件的内容并打印到控制台。

请确保你在运行这个程序之前已经创建了 "output.txt" 文件,否则会出现错误。