Public feed #379600

psicho

public text v1 · immutable
Raw Edit
·published 2007-03-03 11:25 UTC
rendered paste body
char *dtextff(const char *filename,unsigned long lnum)
{
	char *tmp;
	char nline;
	unsigned long i=0;
	unsigned long size=6;
	FILE *fh;

	fh=fopen(filename,"r");
	if(fh==NULL)
	{
		return NULL;
	}


	tmp=calloc(size,sizeof(char));         /*alocating the default size for the first time*/
	if(tmp==NULL)
	{
		return NULL;
	}

	if(lnum==0)                           /*the case when we gonna read the whole file*/
	{
		while( (tmp[i]=fgetc(fh) )!=EOF )  /*checking for the EndOfFile */
		{

			if( i==size-1 )		/* if this is TRUE we need to alocate some more memory*/
			{
				size+=6;
				tmp=realloc(tmp,size*sizeof(char));
				if(tmp==NULL) { return NULL; }
			}
			i++;
		}
	}
	else if( lnum == 1 )                   /*special case for the first line */
	{				       /*this way we can read the very first char ,too */
		while( (tmp[i]=fgetc(fh) )!='\n' )
		{

			if( i==size-1 )
			{
				size*=2;
				tmp=realloc(tmp,size*sizeof(char));
				if(tmp==NULL) { return NULL; }
			}
			i++;
		}
	}
	else if( lnum > 1 )		     /*for any other case ,even if lnum is bigger then the total*/
	{				     /* number of lines the file */
		do
		{
			nline=fgetc(fh);    /*reading the chars from file and testing for new line or EOF */
			if(nline==EOF)	    /* if we get an EOF before i=lnum-1 than its an error...*/
			{ return NULL; }
            if(nline=='\n')
			{
				i++;
			}
		}while( i!=(lnum-1) );		/*repeating until we get to the line we want to read*/
		i=0;
		while( (tmp[i]=fgetc(fh) )!='\n')
		{
			if( i==size-1 )
			{
				size*=2;
				tmp=realloc(tmp,size*sizeof(char));
				if(tmp==NULL) { return NULL; }
			}
			i++;
		}
	}
	else
	{
		return NULL;
	}
        tmp[i]='\0';
	return tmp;
}