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.

#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)));
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).
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.charset.StandardCharsets;
byte[] encoded = Files.readAllBytes(Paths.get(f));
String lines = new String(encoded, StandardCharsets.UTF_8);
lines = io.input(f):read('a')
$lines = file_get_contents('f');
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> };
lines = open(f).read()
lines = File.read(f)
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));
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