The function getContents
has several problems.
char * getContents(char filename[]) {
FILE *fp;
char text[1000];
fp = fopen(filename, "r");
int i = 0;
while (feof(fp)) {
text[i] = fgetc(fp);
i++;
} text[i] = '\0';
return text;
}
The main problem is that you are trying to return pointer to the first element of the local array text
with automatic storage duration that will not be alive after exiting the function.
So the pointer will be invalid.
You could for example define the array as having static storage duration
static char text[1000];
In this case the function may return pointer to the first element of the array like
return text;
because the array will be alive after exiting the function.
But it is better to allocate dynamically memory for the array like
char *text = malloc( 1000 );
Another problem is that you should check whether the specified file was opened successfully.
The condition in this while loop
while (feof(fp)) {
text[i] = fgetc(fp);
i++;
}
is not correct. End of the file can occur in this statement
text[i] = fgetc(fp);
In this case you will write in the array the value of the expression (char)EOF
.
Also you need to check whether you are not writing outside the allocated dynamically array.
The loop can look like
size_t i = 0;
for ( int c; i + 1 < 1000 && ( c = fgetc( fp ) ) != EOF; i++ )
{
text[i] = c;
}
text[i] = '\0';
Also you should close the file before exiting the function
fclose( fp );
The function can look for example the following way
char * getContents( const char filename[])
{
enum { N = 1000 };
char *text = NULL;
FILE *fp = fopen( filename, "r" );
if ( fp != NULL )
{
text = malloc( N * sizeof( char ) );
if ( text == NULL )
{
fclose( fp );
}
else
{
size_t i = 0;
for ( int c; i + 1 < N && ( c = fgetc( fp ) ) != EOF; i++ )
{
text[i] = c;
}
text[i++] = '\0';
fclose( fp );
char *tmp = realloc( text, i * sizeof( char ) );
if ( tmp != NULL ) text = tmp;
}
}
return text;
}
If the file was not opened successfully of if the memory for the array was not allocated the function returns a null pointer.