You can use the fread()
and realloc()
functions within a loop.
At each loop iteration, fread()
is responsible for reading a small block of the input file, while realloc()
is responsible for managing the memory required to accommodate each block read.
Here's an example (tested) illustrating the idea:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_MAX_TAM (128)
int carregar_arquivo( const char * arq, char ** str )
{
unsigned char buf[ BUF_MAX_TAM ] = {0};
int total = 0;
int n = 0;
char * p = NULL;
FILE * pf = NULL;
pf = fopen( arq, "r" );
if(!pf)
return -1;
p = malloc( 1 );
while( (n = fread( buf, 1, sizeof(buf), pf )) != 0 )
{
p = realloc( p, total + n + 1 );
memcpy( p + total, buf, n );
total += n;
};
p[ total ] = './teste config.ini
Lorem ipsum auctor curabitur at justo maecenas hendrerit feugiat, adipiscing augue
accumsan ornareeu nunc iaculis cubilia, sodales quisque bibendum dapibus ullamcorper
ornare diam. consectetur pretium eros velit ante pellentesque taciti ullamcorper interdum
gravida himenaeos viverra mauris luctus hendrerit habitasse arcu fringilla, praesent
habitant mi facilisis curae fames quam sapien.
Bytes lidos: 389
';
*str = p;
fclose(pf);
return total;
}
int main( int argc, char * argv[] )
{
int tam = 0;
char * p = NULL;
tam = carregar_arquivo( argv[1], &p );
printf("%s\n\n", p );
printf("Bytes lidos: %d\n", tam );
free(p);
return 0;
}
Testing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_MAX_TAM (128)
int carregar_arquivo( const char * arq, char ** str )
{
unsigned char buf[ BUF_MAX_TAM ] = {0};
int total = 0;
int n = 0;
char * p = NULL;
FILE * pf = NULL;
pf = fopen( arq, "r" );
if(!pf)
return -1;
p = malloc( 1 );
while( (n = fread( buf, 1, sizeof(buf), pf )) != 0 )
{
p = realloc( p, total + n + 1 );
memcpy( p + total, buf, n );
total += n;
};
p[ total ] = './teste config.ini
Lorem ipsum auctor curabitur at justo maecenas hendrerit feugiat, adipiscing augue
accumsan ornareeu nunc iaculis cubilia, sodales quisque bibendum dapibus ullamcorper
ornare diam. consectetur pretium eros velit ante pellentesque taciti ullamcorper interdum
gravida himenaeos viverra mauris luctus hendrerit habitasse arcu fringilla, praesent
habitant mi facilisis curae fames quam sapien.
Bytes lidos: 389
';
*str = p;
fclose(pf);
return total;
}
int main( int argc, char * argv[] )
{
int tam = 0;
char * p = NULL;
tam = carregar_arquivo( argv[1], &p );
printf("%s\n\n", p );
printf("Bytes lidos: %d\n", tam );
free(p);
return 0;
}