The following line is wrong:
printf("File content is...\n%s", content);
Using printf
with the %s
conversion format specifier requires a null-terminated string. However, your string is not null-terminated.
In order to print a sequence of characters that is not null-terminated, you can write the following instead:
printf( "File content is...\n%.*s", (int)size, content );
Or you can add a terminating null character manually, with the following line:
content[size] = '\0';
However, this will write to the memory buffer content
out of bounds, because you did not allocate any space for the null terminating character. Therefore, you should allocate one additional byte in the malloc
function call.
Another problem is that using ftell
is not a reliable way to determine the length of the file. The ISO C standard does not guarantee that this will work.
For example, on Microsoft Windows, this will give you the length of the file in binary mode (even when the file is opened in text mode). However, the length of the file in text mode is different, because \r\n
line endings get translated to \n
on Microsoft Windows.
Therefore, if you want to read the content of a text file of unknown length, it would probably be better to read one line at a time in a loop, using the function fgets
:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
FILE *fp;
char line[100];
//attempt to open file
fp = fopen( "testingText.txt", "r" );
//verify that file is open
if ( fp == NULL )
{
fprintf( stderr, "error opening file!\n" );
exit( EXIT_FAILURE );
}
printf( "File content is...\n" );
//print one line per loop iteration
while ( fgets( line, sizeof line, fp ) != NULL )
{
//the following code will work even if "fgets" only
//reads a partial line, due to the input buffer not
//being large enough
//print the line to standard output
fputs( line, stdout );
}
//cleanup
fclose( fp );
}