Bug 13152 - fmemopen does not honor append mode
Summary: fmemopen does not honor append mode
Status: RESOLVED FIXED
Alias: None
Product: glibc
Classification: Unclassified
Component: stdio (show other bugs)
Version: unspecified
: P2 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-09-05 02:28 UTC by Rich Felker
Modified: 2015-07-08 15:16 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Last reconfirmed:
fweimer: security-


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Rich Felker 2011-09-05 02:28:10 UTC
fmemopen sets the initial offset correctly for append mode, but otherwise seems to treat append mode just like "r+" (read/update) mode. Writes are not forced to start at the "current size" of the stream, as specified by POSIX:

http://pubs.opengroup.org/onlinepubs/9699919799/functions/fmemopen.html

In other words, opening a stream for append, then seeking to the beginning and attempting a write overwrites the beginning of the buffer rather than appending.
Comment 1 Michael Kerrisk 2012-04-27 20:18:01 UTC
Do you have some example code that demonstrates this?
Comment 2 Michael Kerrisk 2012-04-27 20:48:37 UTC
Okay -- I created an example. See below.

In the below, the "X", should appear at the end of "hello, world", rather than overwriting the first byte.

$ ./a.out x
Initial ftell(): 12
Resetting file position
New ftell(): 0
Xello, world
=====
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>

#define errExit(msg) 	do { perror(msg); exit(EXIT_FAILURE); \
			} while (0)

int
main(int argc, char **argv)
{
    char buf[20] = {"hello, world"};
    FILE *fp = fmemopen(buf, 20, "a+");
    char c;
    int j;

    printf("Initial ftell(): %ld\n", ftell(fp));

    if (argc > 1) {
	printf("Resetting file position\n");
        fseek(fp, 0, SEEK_SET);
        printf("New ftell(): %ld\n", ftell(fp));
    }

    fflush(fp);
    fprintf(fp, "X");
    fflush(fp);
    printf("%s\n", buf);
}
Comment 3 Michael Kerrisk 2012-04-28 03:10:35 UTC
I've added the following text to the fmemopen(3) man page, under bugs:

[[
Specifying append mode ("a" or "a+") for
.BR 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 to append at the end of the stream.
]]
Comment 4 Adhemerval Zanella 2015-07-08 15:16:42 UTC
This is fixed by fdb7d390dd0d96e4a8239c46f3aa64598b90842b.  Closing bug.