Logo

Programming-Idioms

  • C++
  • Haskell
  • Perl
  • Php

Idiom #58 Extract file content to a string

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

$lines = file_get_contents('f');
if ($lines === false) {
    // handle error...
}

lines has the string type if file_get_contents was successful.

You can split this string with explode, or directly use file to read a file into an array of lines.
#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); 
}
do lines <- readFile f; putStr lines
open my $fh, '<', $f;
my $lines = do { local $/; <$fh> };
close $fh;

local $/ tells perl to temporarily (within the braces) clear the "end of line" terminator, causing it to read the entire file as a single string.
#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)));

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