#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
int read_file( char *filename, int *len, char **data )
{
int step = 1024*10;
int file = open( filename, O_RDONLY );
if ( file == -1 )
return -1;
int i = 0;
while ( 1 )
{
*data = realloc( *data, step*(i+1));
if ( data == NULL )
{
close( file );
return -1;
}
int cur_len = read( file, *data+(step*i), step );
if ( cur_len == 0 )
break;
else
*len += cur_len;
i++;
}
close( file );
return 0;
}
int main( int argc, char *argv[] )
{
int len = 0;
char *pdata = NULL;
char *pname = NULL;
if ( argc == 2 )
pname = argv[1];
int nret = read_file( pname, &len, &pdata );
if ( nret != 0 )
{
printf( "read file[%s] fail/n", pname );
}
printf( "file %s :len=%d;/n%s/n", pname, len, pdata );
if ( pdata != NULL )
{
free( pdata);
pdata = NULL;
}
return 0;
}