Logo

Programming-Idioms

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

Idiom #58 Extract file content to a string

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

import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
import java.io.File;
import java.util.Scanner;
File F = new File(f);
try (Scanner s = new Scanner(F)) {
    s.useDelimiter("\\R");
    String n = lineSeparator(),
           lines = s.tokens()
                    .collect(joining(n));
}
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);
#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)));
#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);
}
(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 "os"
b, err := os.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.io.File
File(f).readText()
(with-open-file (stream f)
  (uiop:slurp-stream-string stream))
(defvar *lines*
   (with-open-file (stream f)
      (let ((contents (make-string (file-length stream))))
            (read-sequence contents stream)
      :return contents)))
lines = io.input(f):read('a')
@import Foundation;
NSString *lines=[NSString stringWithContentsOfFile:f encoding:e error:NULL];
$lines = file_get_contents('f');
if ($lines === false) {
    // handle error...
}
uses Classes;
var
 _lines, _f: String;
 SL: TStringList;
begin
  SL := TStringList.Create;
  SL.LoadFromFile(_f);
  _lines := SL.Text;
  SL.Free;
end;
open my $fh, '<', $f;
my $lines = do { local $/; <$fh> };
close $fh;
with open(f) as fo:
    lines = fo.read()
lines = open(f).read()
lines = File.read(f)
use std::fs;
let lines = fs::read_to_string(f).expect("Can't read file.");
use std::io::prelude::*;
use std::fs::File;
let mut file = File::open(f)?;
let mut lines = String::new();
file.read_to_string(&mut lines)?;
import scala.io.Source
val lines = Source.fromFile(filename).getLines().mkString("\n")
| lines |
lines := f asFilename readStream upToEnd.
Dim lines = IO.File.ReadAllText(f)

New implementation...
< >
programming-idioms.org