C Programming: How to read the whole file contents into a buffer

Sunny picture Sunny · Dec 22, 2012 · Viewed 200k times · Source

I want to write the full contents of a file into a buffer. The file actually only contains a string which i need to compare with a string.

What would be the most efficient option which is portable even on linux.

ENV: Windows

Answer

user529758 picture user529758 · Dec 22, 2012

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#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, 1, fsize, f);
fclose(f);

string[fsize] = 0;

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...)