0

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?

Community
  • 1
  • 1
SteveDeFacto
  • 1,317
  • 4
  • 19
  • 35

2 Answers2

2

Use fmemopen(3) instead. This function already facilitate writing/reading to/from memory buffer for you.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
anydot
  • 1,499
  • 9
  • 14
  • Btw - offtopic - I've never understood what that `(3)` means in the `man` page identifiers? And why are you using the `man` page identifier in the first place? – Vilx- Jan 02 '13 at 21:12
  • 2
    If the OP needs a file descriptor, this will not work. *"There is no file descriptor associated with the file stream returned by these functions (i.e., fileno(3) will return an error if called on the returned stream)."* – user7116 Jan 02 '13 at 21:12
  • 3
    @Vilx-: man pages are split into sections; section 3 deals with standard library routines (et al). – user7116 Jan 02 '13 at 21:13
  • 1
    The OP explicitly said he has already tried `fmemopen`. You should probably address his problems in your answer. – Carl Norum Jan 02 '13 at 21:16
  • @Vilx- for reference: http://en.wikipedia.org/wiki/Man_page#Manual_sections – Carl Norum Jan 02 '13 at 21:38
1

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 is read(...) 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, ...).

clstrfsck
  • 14,715
  • 4
  • 44
  • 59