Reason #61 •
March 2nd, 2026
File.read
When programming, reading files is about as common an operation as one can imagine. Wouldn't it be great if there were a simple, obvious, zero-ceremony way to read the contents of a file into a string?
Yes!
Ruby
content = File.read("path/to/file.txt")
JavaScript
const fs = require('fs');
const content = fs.readFileSync('path/to/file.txt', 'utf-8');
What about other languages?
For additional comparison, I asked ChatGPT to provide the most basic/idiomatic ways to read files in a couple of other languages and added them here in rough order of verbosity:
C
#include <stdio.h>
#include <stdlib.h>
char* read_file_utf8(const char* path) {
FILE* f = fopen(path, "rb");
if (!f) return NULL;
if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
long n = ftell(f);
if (n < 0) { fclose(f); return NULL; }
rewind(f);
char* buf = (char*)malloc((size_t)n + 1);
if (!buf) { fclose(f); return NULL; }
size_t read = fread(buf, 1, (size_t)n, f);
fclose(f);
buf[read] = '\0';
return buf; // caller frees
}
C++
#include <fstream>
#include <iterator>
#include <string>
std::ifstream in(path, std::ios::binary);
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>{});
Java
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
String content = Files.readString(Path.of(path), StandardCharsets.UTF_8);
C#
using System.IO;
using System.Text;
string content = File.ReadAllText(path, Encoding.UTF8);
Go
import os
bytes, err := os.ReadFile("path/to/file.txt")
if err != nil {
// handle error
}
content := string(bytes)
Haskell
import qualified Data.ByteString as BS
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
content :: T.Text
content = either (error . show) id . TE.decodeUtf8' =<< BS.readFile path
Rust
use std::fs;
let content: String = fs::read_to_string(path)?;
Python
from pathlib import Path
content = Path(path).read_text(encoding="utf-8")
Clojure
(def content (slurp path :encoding "UTF-8"))
Elixir
content = File.read!(path)
Crystal
content = File.read(path)
Somehow, only Elixir and Crystal provide similarly straightforward APIs for reading files, and they did so by copying Ruby!
History
File.read was added to Ruby in version 1.8 in 2001.