drunkmonkey
drunkmonkey

Reputation: 1181

unlimited size String buffer in c

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

Answers (4)

f3xy
f3xy

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

Nikson Kanti Paul
Nikson Kanti Paul

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

MByD
MByD

Reputation: 137412

You need to dynamically allocate memory, using malloc and realloc.

Upvotes: 3

cnicutar
cnicutar

Reputation: 182734

What you've described is an alternate definition for realloc.

Upvotes: 4

Related Questions