Logo

Programming-Idioms

  • Ada
  • Js

Idiom #58 Extract file content to a string

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

var fs = require('fs');
fs.readFile(f, (err, lines) => {
    if (err) {
        // Handle error...
    }

    // Work with `lines` here.
}

Uses Node-specific file-system API.
#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