mailing list of musl libc
 help / color / mirror / code / Atom feed
* [PATCH] ftello: Need adjust file offset before switching to write
@ 2019-12-18 10:18 wangjianjian (C)
  2019-12-18 13:46 ` Rich Felker
  0 siblings, 1 reply; 5+ messages in thread
From: wangjianjian (C) @ 2019-12-18 10:18 UTC (permalink / raw)
  To: musl; +Cc: Songyunlong (Euler)

Consider below code flow:

FILE *fp = fopen("foobar", "w+");
fputs("hello", fp);
rewind(fp);
fgetc(fp);
ungetc('x', fp);
fputs("world", fp);
off = ftello(fp);

In this code snippet, 'off' will be 10 at last which should be 5 and
file 'foobar's content will be 'helloworld' which is not correct.

The reason is that when do read, we will try our best to get more data
to fill user-provided and the default stream buffer so that the
underlying file offset may not be consistent with stream offset.
As an example above, 'fgetc' will read the whole 5 bytes from 'foobar'
even though we just would like to read one char.

And when we switch to write, we need to adjust the file offset by
decreasing the size of already buffered but not readed data.

Signed-off-by: Wang Jianjian <wangjianjian3@huawei.com>
---
 src/stdio/__towrite.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/src/stdio/__towrite.c b/src/stdio/__towrite.c
index 4c9c66ae..dde3c967 100644
--- a/src/stdio/__towrite.c
+++ b/src/stdio/__towrite.c
@@ -7,6 +7,12 @@ int __towrite(FILE *f)
 		f->flags |= F_ERR;
 		return EOF;
 	}
+
+	/* Adjust offset for already buffered but not readed data */
+	if (f->rend - f->rpos > 0 &&
+	    f->seek(f, f->rpos - f->rend, SEEK_CUR) < 0)
+		return EOF;
+
 	/* Clear read buffer (easier than summoning nasal demons) */
 	f->rpos = f->rend = 0;


BR,
Wang Jianjian



^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2019-12-19  3:19 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2019-12-18 10:18 [PATCH] ftello: Need adjust file offset before switching to write wangjianjian (C)
2019-12-18 13:46 ` Rich Felker
2019-12-19  2:47   ` 答复: [musl] " wangjianjian (C)
2019-12-19  3:03     ` Rich Felker
2019-12-19  3:19       ` 答复: " wangjianjian (C)

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/musl/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).