Note: this is a variation of the accepted answer above.
Here is a way to do this, complete with error checking.
I added a size check to exit when the file was larger than 1 GiB. I did this because the program puts the entire file in a line that can use too much RAM and crash the computer. However, if this does not bother you, you can simply remove it from the code.
#include <stdio.h> #include <stdlib.h> #define FILE_OK 0 #define FILE_NOT_EXIST 1 #define FILE_TO_LARGE 2 #define FILE_READ_ERROR 3 char * c_read_file(const char * f_name, int * err, size_t * f_size) { char * buffer; size_t length; FILE * f = fopen(f_name, "rb"); size_t read_length; if (f) { fseek(f, 0, SEEK_END); length = ftell(f); fseek(f, 0, SEEK_SET); // 1 GiB; best not to load a hole large file in one string if (length > 1073741824) { *err = FILE_TO_LARGE; return NULL; } buffer = (char *)malloc(length + 1); if (length) { read_length = fread(buffer, 1, length, f); if (length != read_length) { *err = FILE_READ_ERROR; return NULL; } } fclose(f); *err = FILE_OK; buffer[length] = '\0'; *f_size = length; } else { *err = FILE_NOT_EXIST; return NULL; } return buffer; }
And check for errors:
int err; size_t f_size; char * f_data; f_data = c_read_file("test.txt", &err, &f_size); if (err) {
Joe Cool Jan 6 '19 at 0:48 2019-01-06 00:48
source share