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

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, fsize, 1, 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…)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)