You can calculate the file's length by using fseek
to move to the end of the file, then ftell
to read the current position (which is the same as the files length (in bytes)), and lastly use rewind
to restore the file pointer to the head of the file:
fseek(fptr, 0, SEEK_END);
file_length = ftell(fptr);
rewind(fptr);
Once you know the file's length, you can dynamically allocate an array large enough to hold it. Here is a complete example:
FILE *fptr;
long str_length;
char *str;
// Open the file.
fptr = fopen(filename, "rb");
// Get the size of the file.
fseek(fptr, 0, SEEK_END);
str_length = ftell(fptr);
rewind(fptr);
// Allocate memory to contain the whole file including the null byte.
str = calloc(str_length + 1, sizeof(char)); // +1 for null byte.
// Read the contents of the file into the buffer.
fread(str, 1, str_length, fptr);
// Null terminate the string.
str[str_length] = '\0';
// Close the file.
fclose(fptr);
// Print the contents of the file.
printf("%s", str);
This example does not include error checking.