title: Make a file pointer read/write to an in-memory location
body: <p>I can make a file pointer write to a file with fopen(). But can I make a file pointer that will make it so calling functions such as fputc or fprintf will write to a pointer in memory? An example of this is ByteArrayOutputStream in java. Also: could I run it in reverse, where a library needs a file pointer to read from, so I allocate memory, and make a new file pointer that will read from this memory location but return EOF when the size of the chunk runs out? (like ByteArrayInputStream in Java). Is there a way to do this in C? For example:</p>
  
  <pre><code>FILE *p = new_memory_file_pointer();
  fprintf(p, "Hello World!\n");
  char *data = get_written_stuff(p);
  printf("%s", data); //will print Hello World!
  </code></pre>
  
  <p>&amp;&amp; / ||</p>
  
  <pre><code>char s[] = "Hello World!\n";
  FILE *p = new_memory_file_pointer_read(s, sizeof(s));
  char *buffer = (char *)malloc( 1024*sizeof(char) );
  fread((void *)buffer, 1, sizeof(s), p);
  printf("%s", buffer); //prints Hello World!
  </code></pre>
  
  <p><strong>EDIT:</strong> To those reading this question years later, in addition to the accepted answer, you should look at <code>open_memstream(3)</code>, which behaves more like these Java classes than <code>fmemopen</code> does. </p>