Reputation: 1181
I'm creating a 'string'
char buffer[BUFFER_SIZE]
but when this gets full, I want to concatenate it onto a pre-existing string, but it needs to have unlimited length and repeat this process until I've read all the data.
Any ideas on how I can do this?
Upvotes: 4
Views: 6061
Reputation: 774
I have used open_memstream to achieve this in the past.
This function opens a stream for writing to a buffer. The buffer is allocated dynamically and grown as necessary, using malloc. After you’ve closed the stream, this buffer is your responsibility to clean up using free or realloc.
https://www.gnu.org/software/libc/manual/html_node/String-Streams.html
#include <stdio.h>
int
main (void)
{
char *bp;
size_t size;
FILE *stream;
stream = open_memstream (&bp, &size);
fprintf (stream, "hello");
fflush (stream);
printf ("buf = `%s', size = %zu\n", bp, size);
fprintf (stream, ", world");
fclose (stream);
printf ("buf = `%s', size = %zu\n", bp, size);
return 0;
}
Upvotes: 8
Reputation: 3440
you can try to use realloc
char *temp = NULL;
char *buffer = (char*) realloc (temp, BUFFER_SIZE*sizeof(char));
you will get dynamic amount of memory based on BUFFER_SIZE
Upvotes: 2