0

How do I use a char array to be the data storage for a FILE stream?

char buffer[max_len];
FILE *fp = fopen(<I want to use data in buffer variable as file data>, "r");

The goal is to have data ready in fp for the following behavior:

execl("/bin/cat", "cat",  fp, (char *)NULL);

Additionally, when using fmemopen (as suggested):

char buf[] = "hello";

FILE *fp = fmemopen(buf, strlen(buf), "w");
execl("/usr/bin/echo", "echo",  fp, (char *)NULL);

I get mangled output..

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
moimoi
  • 171
  • 1
  • 7
  • 2
    As I understand, you need fmemopen() function. – grungegurunge Oct 02 '18 at 12:36
  • You can also [read an write from /dev/shm](https://www.cyberciti.biz/tips/what-is-devshm-and-its-practical-usage.html) – David Ranieri Oct 02 '18 at 12:40
  • 2
    You are executing another process, you cannot pass a FILE* to it and have it know how to read from that. If your real issue is to execl() another process and have it read data from your memory, there are other ways to do that. (and if the data is reasonably small, the echo example could be done by `execl("/usr/bin/echo", "echo", buf, (char *)NULL);` If you want to learn how to use fmemopen() though, you can't use it with execl() in this way. – nos Oct 02 '18 at 20:35

1 Answers1

3

If you are using C and the GNU C Library, or any POSIX compliant implementation, You can use fmemopen which works exactly as you expect.

If you want to do this in portable ISO C, fmemopen is unfortunately not available.

There are however examples of libraries doing this in a portable way, eg. https://github.com/Snaipe/fmem.

This makes use of the funopen function which allows associating stream operations with user-supplied functions.

If you target Windows, the situation is a little more complicated, with some insights found in this answer: https://stackoverflow.com/a/50087392/393701.

SirDarius
  • 41,440
  • 8
  • 86
  • 100
  • [`fmemopen()` is part of the POSIX standard](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fmemopen.html), so it's pretty portable. – Andrew Henle Oct 02 '18 at 12:50