Skip to content

Instantly share code, notes, and snippets.

@donjajo
Last active May 5, 2019 21:12
Show Gist options
  • Save donjajo/be303054d33f7a096b2aabede897055d to your computer and use it in GitHub Desktop.
Save donjajo/be303054d33f7a096b2aabede897055d to your computer and use it in GitHub Desktop.
Replica of file_get_contents() function in PHP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *file_get_contents();
int main() {
char *str = file_get_contents( "test.txt" );
printf( "%s", str );
free( str );
return 0;
}
char *file_get_contents( char file[] ) {
FILE *f = fopen( file, "r" );
int str_size = sizeof( char ) * 4;
char *content = ( char* ) malloc( str_size );
if( f == NULL ) {
perror( "Unable to open file" );
return "";
}
if( content != NULL ) {
char str_content[ str_size ];
int i = 1;
while( fgets( str_content, str_size, f ) != NULL ) {
content = ( char * ) realloc( content, ( str_size * i ) );
strcat( content, str_content );
i++;
}
return content;
}
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment