Skip to content

Commit b4551fe

Browse files
committed
fmemopen: set position to end when writing in append mode
This matches the glibc behaviour and seems more correct to me.
1 parent 208f19d commit b4551fe

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

newlib/libc/tinystdio/fmemopen.c

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
#include <unistd.h>
4343

4444
#define __MALL 0x01
45+
#define __MAPP 0x02
4546

4647
struct __file_mem {
4748
struct __file_ext xfile;
@@ -56,12 +57,13 @@ static int
5657
__fmem_put(char c, FILE *f)
5758
{
5859
struct __file_mem *mf = (struct __file_mem *)f;
60+
size_t pos = mf->mflags & __MAPP ? mf->size : mf->pos;
5961
if ((f->flags & __SWR) == 0) {
6062
return _FDEV_ERR;
61-
} else if (mf->pos < mf->bufsize) {
62-
mf->buf[mf->pos++] = c;
63-
if (mf->pos > mf->size) {
64-
mf->size = mf->pos;
63+
} else if (pos < mf->bufsize) {
64+
mf->buf[pos++] = c;
65+
if (pos > mf->size) {
66+
mf->size = pos;
6567
/* When a stream open for update (the mode argument includes '+') or
6668
* for writing only is successfully written and the write advances
6769
* the current buffer end position, a null byte shall be written at
@@ -70,6 +72,7 @@ __fmem_put(char c, FILE *f)
7072
mf->buf[mf->size] = '\0';
7173
}
7274
}
75+
mf->pos = pos;
7376
return (unsigned char)c;
7477
} else {
7578
return _FDEV_EOF;
@@ -182,6 +185,7 @@ fmemopen(void *buf, size_t size, const char *mode)
182185
/* For append the position is set to the first NUL byte or the end. */
183186
initial_pos = (mflags & __MALL) ? 0 : strnlen(buf, size);
184187
initial_size = initial_pos;
188+
mflags |= __MAPP;
185189
} else if (mode[0] == 'w') {
186190
initial_size = 0;
187191
/* w+ mode truncates the buffer, writing NUL */

0 commit comments

Comments
 (0)