How to make a buffer?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Osoascam
    New Member
    • Feb 2007
    • 21

    #1

    How to make a buffer?

    Hi! I made this code in order to "create" a buffer...
    It works perfectly when reading from console, but it just doesn't work for redinf from files.
    (Read after the function for the code explanation)
    NAME is a class variable, char*

    Code:
    void buffer(FILE* entrada, char separador)     //entrada is input (sdtin for consol)
    {
    	int numChars = 2;                                //# of characters read
    	char* aux;
    	buff = (char*)malloc(sizeof(char)*numChars);
    	NAME = (char*)malloc(sizeof(char)*numChars);
    	aux = (char*)malloc(sizeof(char)*numChars);
    	fgets(buff,(numChars),entrada);
    	*NAME = '\0';
    	do
    	{
    		aux = (char*)malloc(strlen(NAME)+numChars);
    		strcpy(aux, NAME);
    		free(NAME);
    		NAME = (char*)malloc(strlen(aux)*2+numChars);
    		strcpy(NAME, aux);
    		strncat(NAME, buff, numChars);
    		free(buff);
    		numChars = numChars*2;
    		buff = (char*)malloc(numChars+1);
    		fgets(buff,(numChars),entrada);
    
    	}
    	while (strchr(buff, separador) == NULL);       //if "separador" isnt in the line
    	strncat(NAME,buff,strlen(buff));
    	NAME[strlen(NAME)-1] = '\0';
    	free(aux);
    	free(buff);
    }
    OK, so this is what it does:
    Three variables: buff, NAME and aux
    For readin' from console, the inputs are buffer(stdin,'\ n')
    Buff grows double, as well as NAME and aux. Normally, NAME and aux contain the same, but I free NAME and aux form making them bigger.

    So, why it doesn't work for files if I just put
    buffer(file-name, EOF)
    ?

    Thank you!!
  • priyachari
    New Member
    • Jan 2007
    • 11

    #2
    Hi,

    Your File Pointer entrada, in case of a file ,should specify the mode in which the file is to be opened..

    say,
    entrada = fopen(FilePath, "r");

    where filepath is the actual file with its path.

    Comment

    • Osoascam
      New Member
      • Feb 2007
      • 21

      #3
      Thank you, but... It still doesn't work
      The problem is it keeps reading forever

      Comment

      Working...