简体   繁体   中英

using setvbuf to make memory buffer act like FILE*

I need a cross platform way of treating memory buffer as FILE* . I have seen other questions which point out that there is no portable way to do this (fmemopen in linux is what I need but it fails on Windows platform).

I have tried using the setvbuf and it seems to work. Can anyone please point out the exact problem of using setvbuf function?

Also , I have seen the C standard draft WG14/N1256 and 7.19.5.6 says:

the contents of array at any time are indeterminate.

I don't understand if I use my own buffer how can its contents be indeterminate?

EDIT : Thanks for all the answers. Not using this method anymore.

No really, there's no portable way to do this.

Using setvbuf may appear to work but you're really invoking undefined behavior, and it will fail in unexpected ways at unexpected times. The GNU C library does have fmemopen(3) as an extension, as you mentioned, but it's not portable to non-GNU systems.

If you're using some library that requires a FILE* pointer and you only have the required data in memory, you'll just have to write it out to a temporary file and pass in a handle to that file. Ideally, your library should provide an alternative function that takes a memory pointer instead of a file pointer, but if not, you're out of luck (and you should complain to the library writer about that deficiency).

Function setvbuf() is used to tell the FILE the memory to be used as buffer, but it does not specify how this memory will be used: that's up to the implementation.

Thus, the contents of the buffer are indeterminate at any time, and if it happens to work for you, it is just by chance.

It depends on what you want to do with the buffer/FILE*. You can certainly perform simple operations and get away with them, but you cannot guarantee that all of the FILE* operations will perform as expected on your memory buffer.

Sorry, there is simply no cross-platform one-liner to get full FILE* characteristics, I've tried myself many times haha

what you can try:

  • #define-wrapped OS-specific logic
  • Look further into the interface you are trying to interact with. At some point it just plays with a buffer anyway. Then splice in your buffer. This is what I did.
  • Your technique + faith.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM