Possible Duplicate:
How to get file descriptor of buffer in memory?
I’m trying to force a library that uses a FILE class to use a buffer in memory instead of a file. I tried fmemopen, however, the library uses fileno which returns -1 and causes the library to crash. So I read that I need a file descriptor and I could use the pipe command to make one. I don’t fully understand what I did but I got it to work. However, I don’t know if what I did is actually safe. So here is the code:
int fstr[2];
pipe(fstr);
write(fstr[1], src, strlen(src));
close(fstr[1]);
FILE* file = fdopen( fstr[0], "r" );
So is this safe?
If you really need a file handle, this is as good as anything I can think of.
One possible issue you may run into is that the buffer size for a pipe is limited. If your string is larger than the buffer size, the
write(...)to the pipe will block until some data isread(...)from the other end.Ideally you would have a worker thread writing to the pipe, but if this is not possible/too hard, you can possibly adjust the pipe buffer size through
fcntl(fd, F_SETPIPE_SZ, ...).