Logo

Programming-Idioms

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

Idiom #58 Extract file content to a string

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

import "os"
b, err := os.ReadFile(f)
if err != nil {
	// Handle error...
}
lines := string(b)

In Go it is idiomatic to inspect an error value before moving on.

lines is 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