Reputation: 1131
I try to map a char * to an in-memory FILE* with fmemopen. I just found out that fmemopen will not give me a file descriptor. Is there a way to get an in-memory FILE with FD?
char * data = ... data ...;
FILE *fid = fmemopen(data, 172, "r");
int fd = fileno(fid);
if(fd < 0)
std::cout << "BAD" << std::endl;
else
std::cout << "GOOD" << std::endl;
Upvotes: 1
Views: 1400
Reputation: 607
Have a look and see if shm_open()
in conjunction with fdopen()
does what you want.
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
FILE *f = NULL;
int fd = 0, n = 0;
char buffer[6] = "hello";
fd = shm_open("myfile", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(fd<0) {
printf("failed to shm_open\n");
exit(1);
}
f = fdopen(fd,"w+");
if(!f) {
printf("failed to fdopen\n");
exit(1);
}
n = fwrite(buffer, sizeof(char), sizeof(buffer), f);
printf("wrote %d bytes", n);
fclose(f);
}
Upvotes: 3
Reputation: 74018
fopen
is based on the open
system call and therefore has a corresponding file descriptor.
fmemopen
on the other side is a pure library implementation and doesn't need a system file descriptor. See also the NOTES
section on fileno
.
Upvotes: 0