Will McConnell
Will McConnell

Reputation: 19

Reading in File to String

I'm trying to read the contents of a file into a string, and am having trouble with allocating memory for the string. I am reading in the file line by line, b/c I want to skip the first two lines.

int counter=1;
char *myhtml;
myhtml=calloc(1,10);

while ((read = getline(&line, &len, fp)) != -1) 
{
    if (counter>2)
    {
        //printf("%s",line);
        myhtml=realloc(myhtml,sizeof(char)*strlen(line));
        strcat(myhtml,line);                        
    }
    counter++;
}

How would I go about reallocating memory for this kind of function?

Upvotes: 1

Views: 104

Answers (2)

user3629249
user3629249

Reputation: 16540

there are several 'problems' with the posted code.

Rather than my detailing each problem. just compare the posted code with the following

The following code eliminates those 'problems' and is faster as 'counter' is not being tested nor incremented, nor is 'counter' cluttering the stack.

char *myhtml = NULL; // the accumulated lines
char *line = NULL;   // the current line
int len;             // set by the readline() function

// read and discard first two lines
getline(&line, &len, fp);
free(line);
line = NULL;
getline(&line, &len, fp);
free(line);
line = NULL;

while ((getline(&line, &len, fp)) != -1)
{
    char *temp = NULL; // so do not lose pointer to already allocated memory
    if( NULL ==(temp=realloc(myhtml,strlen(myhtml)+len+1) ) ) )
    { // realloc failed
        perror( "realloc failed");
        free( myhtml ); // cleanup
        free( line );   // cleanup
        exit( EXIT_FAILURE);
    }

    // implied else, realloc successful

    myhtml = temp;
    strcat(myhtml,line);
    free(line); // getline() performs a hidden malloc(), so have to free())
    line = NULL;  // reset for next iteration
}

Upvotes: 0

bgeschka
bgeschka

Reputation: 102

As long as you're just reading in a file, you could just allocate the whole space for the file at once like:

struct stat statbuf;
stat("testfile", &statbuf);
char *myhtml = calloc(1,statbuf.st_size);

and maybe free the rest after you're done reading in. Which is way cheaper because malloc is pretty expensive

Upvotes: 2

Related Questions