Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #58 Extract file content to a string

Create string lines from the content of the file with filename f.

lines = File.read(f)
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int err = 0;
int fd = 0;
void * ptr = NULL;
struct stat st;
if ((fd = open (f, O_RDONLY))
&& (err = fstat (fd, &st)) == 0
&& (ptr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != -1) {
    const char * lines = ptr;
    puts (lines);
    munmap (ptr, st.st_size);
    close (fd);
}
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
FILE *file;
size_t len=0;
char *lines;
assert(file=fopen(f,"rb"));
assert(lines=malloc(sizeof(char)));

while(!feof(file))
{
	assert(lines=realloc(lines,(len+0x1000)*sizeof(char)));
	len+=fread(lines,1,0x1000,file);
}

assert(lines=realloc(lines,len*sizeof(char)));
(def lines (slurp f))
#include <sstream>
std::string fromFile(std::string _f)
{
    std::ifstream t(_f);
    t.seekg(0, std::ios::end);
    size_t size = t.tellg();
    std::string buffer(size, ' ');
    t.seekg(0);
    t.read(&buffer[0], size); 
}
System.IO;
string lines = File.ReadAllText(f);
import std.file;
string lines = cast(string) read(f, size_t.max);
import std.file;
auto lines = f.readText;
import "dart:io";
var lines = new File(f).readAsStringSync();
lines = File.read!(f)
{ok, Lines} = file:read_file(F).
program p
   character(len=:),allocatable :: s
   open(unit=10,file='myfile',access='stream')
   inquire(10,size=i)
   allocate(character(len=i) :: s)
   read(10)(s(j:j),j=1,i)
   write(*,*)s
end program p
import "io/ioutil"
b, err := ioutil.ReadFile(f)
if err != nil {
	// Handle error...
}
lines := string(b)
do lines <- readFile f; putStr lines
var fs = require('fs');
fs.readFile(f, (err, lines) => {
    if (err) {
        // Handle error...
    }

    // Work with `lines` here.
}
import java.nio.file.Files;
import java.nio.charset.StandardCharsets;
byte[] encoded = Files.readAllBytes(Paths.get(f));
String lines = new String(encoded, StandardCharsets.UTF_8);
import java.io.File
File(f).readText()
lines = io.input(f):read('a')
$lines = file_get_contents('f');
if ($lines === false) {
    // handle error...
}
Classes
var
 _lines, _f: String;
 SL: TStringList;
begin
  SL := TStringList.Create;
  SL.LoadFromFile(_f);
  _lines := SL.Text;
  SL.Free;
end;
my $lines = do { local $/; <$FH> };
with open(f) as fo:
    lines = fo.read()
lines = open(f).read()
use std::io::prelude::*;
use std::fs::File;
let file = try!(File::open(f));
let mut lines = String::new();
try!(file.read_to_string(&mut lines));
use std::fs;
let lines = fs::read_to_string(f).expect("Can't read file.");
import scala.io.Source
val lines = Source.fromFile(filename).getLines().mkString("\n")
Dim lines = IO.File.ReadAllText(f)

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org