Last active
May 5, 2019 21:12
-
-
Save donjajo/be303054d33f7a096b2aabede897055d to your computer and use it in GitHub Desktop.
Replica of file_get_contents() function in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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