Logo

Programming-Idioms

  • Python
  • C++
  • C

Idiom #58 Extract file content to a string

Create the 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)));
#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);
}

Mapping the whole file into the process address space avoids allocating memory.
lines = open(f).read()

For more complicated file operations, use a context manager with with
with open(f) as fo:
    lines = fo.read()

The with statement creates a contextmanager, which automatically handles closing the file for you when you're done. Without this, you should be manually closing file objects so that you are not relying on the garbage collector to do this for you.
#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); 
}
(def lines (slurp f))

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