简体   繁体   English

fmemopen和open_memstream有什么区别?

[英]What is the difference between fmemopen and open_memstream?

While reading through the GNU documentation on string streams I found two similar functions that do very similar things: 在阅读有关字符串流的GNU文档时,我发现了两个类似的函数,它们执行非常相似的操作:

FILE * fmemopen (void *buf, size_t size, const char *opentype)
FILE * open_memstream (char **ptr, size_t *sizeloc)

From reading the documentation, it seems open_memstream should be used for opening an output stream and fmemopen for input. 从阅读文档,似乎open_memstream应该用于打开输出流和fmemopen用于输入。 What catches me is the opentype argument that you can pass to fmemopen . 什么抓住我的是opentype参数可以传递到fmemopen

The linux manpage explains : linux手册页说明

If buf is specified as NULL, then fmemopen() dynamically allocates a buffer size bytes long. 如果将buf指定为NULL,则fmemopen()动态分配一个缓冲区大小为bytes的字节。 This is useful for an application that wants to write data to a temporary buffer and then read it back again. 这对于想要将数据写入临时缓冲区然后再次读取的应用程序非常有用。 The buffer is automatically freed when the stream is closed. 关闭流时,将自动释放缓冲区。 Note that the caller has no way to obtain a pointer to the temporary buffer allocated by this call (but see open_memstream() below). 请注意,调用者无法获取指向此调用分配的临时缓冲区的指针(但请参阅下面的open_memstream())。

So what would be the point of using open_memstream if fmemopen can handle opening an input/output stream? 那么如果fmemopen可以处理打开输入/输出流,那么使用open_memstream fmemopen什么意义呢?

With fmemopen , the buffer is allocated at or before the open, and doesn't change size later. 使用fmemopen ,缓冲区在打开时或之前分配,并且稍后不会更改大小。 If you're going to write to it, you have to know how big your output will be before you start. 如果您要写信给它,您必须知道在开始之前您的输出有多大。 With open_memstream the buffer grows as you write. 使用open_memstream ,缓冲区会随着您的编写而增长。

The FILE* for open_memstream is write-only open_memstreamFILE*是只写的

POSIX http://pubs.opengroup.org/onlinepubs/9699919799/functions/open_memstream.html POSIX http://pubs.opengroup.org/onlinepubs/9699919799/functions/open_memstream.html

These functions are similar to fmemopen() except that the memory is always allocated dynamically by the function, and the stream is opened only for output. 这些函数类似于fmemopen(),除了内存总是由函数动态分配,并且仅为输出打开流。

So there is a second difference besides the dynamic allocation: the file is opened only for writing. 因此除了动态分配之外还有第二个区别:文件仅在写入时打开。

And since you can't change the flags of open streams, you shouldn't be able to read from the stream. 由于您无法更改开放流的标志,因此您无法从流中读取。

However it seems some implementations might allow this: Can I read stream produced by open_memstream()? 然而,似乎某些实现可能允许这样: 我可以读取open_memstream()生成的流吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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