Reputation: 201
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..
Upvotes: 1
Views: 1371
Reputation: 42899
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.
Upvotes: 3