What you mean is to get the whole file content, that is easily done this way
#include <stdio.h>
#include <stdlib.h>
char *readFileContent(const char *const filename)
{
size_t size;
FILE *file;
char *data;
file = fopen(filename, "r");
if (file == NULL)
{
perror("fopen()\n");
return NULL;
}
/* get the file size by seeking to the end and getting the position */
fseek(file, 0L, SEEK_END);
size = ftell(file);
/* reset the file position to the begining. */
rewind(file);
/* allocate space to hold the file content */
data = malloc(1 + size);
if (data == NULL)
{
perror("malloc()\n");
fclose(file);
return NULL;
}
/* nul terminate the content to make it a valid string */
data[size] = '\0';
/* attempt to read all the data */
if (fread(data, 1, size, file) != size)
{
perror("fread()\n");
free(data);
fclose(file);
return NULL;
}
fclose(file);
return data;
}
int main()
{
char *content;
content = readFileContent(inputFilename);
if (content != NULL)
{
printf("%s\n", content);
free(content);
}
reutrn 0;
}
and this will of course fail in the rare case where the file size exceeds the available RAM, but it will not cause undedined behavior, because that case is handeled as a malloc()
failure.