Comparisment

   - compare programming languages by example

26

Reading files

Read the contents of files.

Created by sam

Add a new answer

Either add an answer for a new language or add an alternative solution.
A description is only necessary when the code is not suitably 'obvious' or to justify an alternative approach.

Haskell

getFileContents :: IO String
getFileContents = readFile "filename"

From the prelude, read a file into a 'String' type.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

import Prelude hiding (readFile)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (readFile)

getFileContents :: IO ByteString
getFileContents = readFile "fileName"

Read a file into the strict 'ByteString' type.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

import Prelude hiding (readFile)
import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Lazy.Char8 (readFile)

getFileContents :: IO ByteString
getFileContents = readFile "fileName"

Read a file into the lazy 'ByteString' type.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Haskell

import Data.Text (Text)
import Data.Text.IO (readFile)

getFileContents :: IO Text
getFileContents = readFile "fileName"

Read a file into a strict 'Text' type.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.

Python

def getFileContents():
  return (open('fileName', 'r').read().close())

Open a file object in 'r'ead mode and read the entire contents.

Created by: sam

Edit this answer

Edit the language, code and description simultaneously.