I want to read the contents of a file into a buffer.
What would be the most efficient and portable option?
Portability between Linux and Windows is a headache, since Linux is a POSIX-conformant system with high-quality toolchain for C; whereas, Windows does not.
If you stick to the standard and don't mind a race condition (between getting the file's size and reading the contents), this may suffice:
#include <stdio.h>
#include <stdlib.h>
FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */
char *string = malloc(fsize + 1);
fread(string, fsize, 1, f);
fclose(f);
string[fsize] = 0;
// use the string, then ...
free(string);
Here string
will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows).
If you do care about the race condition, see this other answer.