Vous êtes sur la page 1sur 7

Name

fmemopen, open_memstream, open_wmemstream - open memory as stream

Synopsis
#include <stdio.h>
FILE *fmemopen(void *buf, size_t size, const char *mode);
FILE *open_memstream(char **ptr, size_t *sizeloc);

#include <wchar.h>
FILE *open_wmemstream(wchar_t **ptr, size_t *sizeloc);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):


fmemopen(), open_memstream(), open_wmemstream():
Since glibc 2.10:
_XOPEN_SOURCE >= 700 || _POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_GNU_SOURCE

Description
The fmemopen() function opens a stream that permits the access specified by mode. The stream
allows I/O to be performed on the string or memory buffer pointed to by buf. This buffer must be
at least size bytes long.

The argument mode is the same as forfopen(3). If mode specifies an append mode, then the initial
file position is set to the location of the first null byte ('\0') in the buffer; otherwise the initial file
position is set to the start of the buffer. Since glibc 2.9, the letter 'b' may be specified as the second
character in mode. This provides "binary" mode: writes don't implicitly add a terminating null
byte, and fseek(3) SEEK_END is relative to the end of the buffer (i.e., the value specified by the
size argument), rather than the current string length.

When a stream that has been opened for writing is flushed (fflush(3)) or closed (fclose(3)), a null
byte is written at the end of the buffer if there is space. The caller should ensure that an extra byte
is available in the buffer (and that size counts that byte) to allow for this.

Attempts to write more than size bytes to the buffer result in an error. (By default, such errors will
only be visible when the stdio buffer is flushed. Disabling buffering with setbuf(fp, NULL) may be
useful to detect errors at the time of an output operation. Alternatively, the caller can explicitly set
buf as the stdio stream buffer, at the same time informing stdio of the buffer's size, using
setbuffer(fp, buf, size).)

In a stream opened for reading, null bytes ('\0') in the buffer do not cause read operations to return
an end-of-file indication. A read from the buffer will only indicate end-of-file when the file pointer
advancessize bytes past the start of the buffer.
If buf is specified as NULL, then fmemopen() dynamically allocates a buffer size bytes long. 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).

The open_memstream() function opens a stream for writing to a buffer. The buffer is dynamically
allocated (as with malloc(3)), and automatically grows as required. After closing the stream, the
caller should free(3) this buffer.

When the stream is closed (fclose(3)) or flushed (fflush(3)), the locations pointed to by ptr and
sizelocare updated to contain, respectively, a pointer to the buffer and the current size of the
buffer. These values remain valid only as long as the caller performs no further output on the
stream. If further output is performed, then the stream must again be flushed before trying to
access these variables.

A null byte is maintained at the end of the buffer. This byte is not included in the size value stored
atsizeloc.

The stream's file position can be changed with fseek(3) or fseeko(3). Moving the file position past
the end of the data already written fills the intervening space with zeros.

The open_wmemstream() is similar to open_memstream(), but operates on wide characters instead


of bytes.

Return Value
Upon successful completion fmemopen(), open_memstream() and open_wmemstream() return a
FILEpointer. Otherwise, NULL is returned and errno is set to indicate the error.

Versions
fmemopen() and open_memstream() were already available in glibc 1.0.x. open_wmemstream()
is available since glibc 2.4.

Conforming To
POSIX.1-2008. These functions are not specified in POSIX.1-2001, and are not widely available
on other systems. It specifies that 'b' in mode shall be ignored. However, Technical Corrigendum 1
adjusts the standard to allow implementation-specific treatment for this case, thus permitting the
glibc treatment of 'b'.

Notes
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).
Bugs
In glibc before version 2.7, seeking past the end of a stream created by open_memstream() does
not enlarge the buffer; instead the fseek(3) call fails, returning -1.

If size is specified as zero, fmemopen() fails with the error EINVAL. It would be more consistent
if this case successfully created a stream that then returned end of file on the first attempt at
reading. Furthermore, POSIX.1-2008 does not specify a failure for this case.

Specifying append mode ("a" or "a+") for fmemopen() sets the initial file position to the first null
byte, but (if the file offset is reset to a location other than the end of the stream) does not force
subsequent writes to append at the end of the stream.

If the mode argument to fmemopen() specifies append ("a" or "a+"), and the size argument does
not cover a null byte in buf then, according to POSIX.1-2008, the initial file position should be set
to the next byte after the end of the buffer. However, in this case the glibc fmemopen() sets the
file position to -1.

To specify binary mode for fmemopen() the 'b' must be the second character in mode. Thus, for
example, "wb+" has the desired effect, but "w+b" does not. This is inconsistent with the treatment
of mode byfopen(3).

The glibc 2.9 addition of "binary" mode for fmemopen() silently changed the ABI: previously,
fmemopen() ignored 'b' in mode.

Example
The program below uses fmemopen() to open an input buffer, and open_memstream() to open a
dynamically sized output buffer. The program scans its input string (taken from the program's first
command-line argument) reading integers, and writes the squares of these integers to the output
buffer. An example of the output produced by this program is the following:
$ ./a.out '1 23 43'
size=11; ptr=1 529 1849

Program source
#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define handle_error(msg) \
do { perror(msg); exit(EXIT_FAILURE); } while (0)

Int main(int argc, char *argv[])


{
FILE *out, *in;
int v, s;
size_t size;
char *ptr;

if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}

in = fmemopen(argv[1], strlen(argv[1]), "r");


if (in == NULL)
handle_error("fmemopen");

out = open_memstream(&ptr, &size);


if (out == NULL)
handle_error("open_memstream");

for (;;) {
s = fscanf(in, "%d", &v);
if (s <= 0)
break;
s = fprintf(out, "%d ", v * v);
if (s == -1)
handle_error("fprintf");
}
fclose(in);
fclose(out);
printf("size=%ld; ptr=%s\n", (long) size, ptr);
free(ptr);
exit(EXIT_SUCCESS);

With fmemopen, the buffer is allocated at or before the open, and doesn't change size later. 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.

Here is a very neat function in the posix 2008 standard: open_memstream(). You use it like this:
char* buffer = NULL;
size_t bufferSize = 0;
FILE* myStream = open_memstream(&buffer, &bufferSize);
fprintf(myStream, "You can output anything to myStream, just as you can with stdout.\n");
myComplexPrintFunction(myStream); //Append something of completely unknown size.
fclose(myStream); //This will set buffer and bufferSize.
printf("I can do anything with the resulting string now. It is: \"%s\"\n", buffer);
free(buffer);
Is there a good alternative to open_memstream? A number of platforms (solaris among them) don't
provide this [yet].

The closest would be asprintf(), which is also not provided by all platforms. All other alternatives
either have severe security problems because they can overrun the supplied buffer (sprintf() and
fmemopen()), or force you to run the string generation twice to avoid failing when your
preallocated buffer is too small (snprintf()). Only asprintf() and open_memstream() deliver safe
single pass semantics. However, if asprintf() would work for you, you can easily implement your
own version via two passes of vsprintf()
For example from the refference:
#include <stdio.h>
int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n",buffer,n);
return 0;
}

Output:
[5 plus 3 is 8] is a string 13 chars long

Update: Based on recommendations in comments: Use snprinft as it is more secure (prevents buff
er overflow attacks) and is portable.
#include <stdio.h>
int main ()
{
int sizeOfBuffer = 50;
char buffer [sizeOfBuffer];
int n, a=5, b=3;
n= snprintf (buffer, sizeOfBuffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a string %d chars long\n",buffer,n);
return 0;
}
Notice that snprintf second argument is actually the max allowed size to use, so you can put it to a
lower value than sizeOfBuffer, however for your case it would be unnecessary. Snprintf only
writes SizeOfBuffer -1 chars and uses the last byte for the termination character.

And just to piss off everyone from the embbed and security department, here is a link to http://
www. cplusplus.com/reference/cstdio/snprintf/

Don't use sprintf(), virtually any use of sprintf() will explode some time. Use asprintf() instead, it
will malloc a buffer of the required length for you.
Or snprintf in portable code. Also, please don't link to cplusplus.com, that website is full of errors.
cppreference.com is better.

Also, sprintf and vsprintf have security concerns. codecogs.com/library/computing/c/stdio.h/… "


The sprintf and vsprintf functions are easily misused in a manner which enables malicious users to
arbitrarily change a running program's functionality through a buffer overflow attack. Because
sprintf and vsprintf assume an infinitely long string, callers must be careful not to overflow the
actual space; this is often hard to assure. For safety, programmers should use the snprintf interface
instead. "

Thanks for pointing out the flaw of sprintf. It is ofcourse a good virtue to teach good manners.
Usage of cplusplus.com vs cpprefference: It might be that cplusplus has some errors, and probably
due to the examples that in several places might provide a good example on a specific reference,
but uses problematic functions (like sprintf) along the example. Personally i find cplusplus.com a
lot easiere to read, and in some applications it is more important to understand than be correct.

Getting a warning:
Initialization between types "struct {...}*" and "int" is not allowed.
on this line:
FILE *om= open_memstream(&ls_sh, &len);

First problem: the open_memstream is not a standard C library function. It's defined by some
versions of POSIX. The man page on my Linux system (Ubuntu 16.10) says:
CONFORMING TO
POSIX.1-2008. These functions are not specified in POSIX.1-2001, and are not widely available
on other systems.

You might be trying to compile code written for another system (one that provides open_memstr
eam on a different system (one that doesn't provide open_memstream). Or it might be available on
your system, but you haven't provided whatever incantation is needed to make it visible. A
conforming ISO C implementation is forbidden to define functions in standard headers other than
the ones defined by the C standard (unless they use reserved names, which doesn't apply here), but
typically there's a way to request conformance to POSIX rather than just to ISO C. If that's the
case, the man page on your system should tell you what you need to do: man open_memstream.
You might need to define a macro or pass a command-line argument to the compiler.
(This all might have been simpler if all POSIX-specific functions were declared in separate
headers rather than sharing the C-standard ones line <stdio.h>, but there are historical reasons why
that wasn't done.)

Second problem: You've also asked why you only get a warning. Prior to the 1999 ISO C standard,
it was legal to call an undeclared function. The compiler would create an implicit declaration,
assuming that the function takes whatever arguments you've passed it and returns a result of type
int. If the actual function doesn't match that assumption, the behavior is undefined. The 1999
standard dropped this "implicit int" rule, making a call to an undeclared function a constraint
violation. But compilers aren't required to reject code that violates such a rule; printing a warning
and continuing to compile is valid. Which means that you should take all warnings from your C
compiler very seriously.
(If your system doesn't have open_memstream, you might look for fmemopen, which appears to
be similar. It's also defined by POSIX and not by ISO C, so the same considerations apply.)

fmemopen 应用场合较多,比如有些文件不支持内存操作,但是支持文件操作的。
#include <string.h>
#include <stdio.h>
static char buff[] = "Mayuyu is from Japan";
int main(int argc, char **argv)
{
int len = strlen(buff);
FILE *fd = fmemopen(buff, len, "r");
if(fd == NULL)
{
printf("get file error!\n");
return -1;
}

char ch;
while((ch = fgetc(fd)) != EOF)
printf("%c", ch);
puts("");
fclose(fd);
return 0;
}

Vous aimerez peut-être aussi