首页 > 解决方案 > fseek/fsetpos may discard stream buffer?

问题描述

In the C standard for fopen regarding files opened in update mode (C11 7.21.5.3/7), output followed by input requires an intervening call to fflush or a file positioning function (fseek, fsetpos, or rewind). However, none of the file positioning functions are required to do anything regarding the output buffer.

The POSIX standard maintains the same requirement for fopen and update mode. As with the C standard, fsetpos is not required to do anything with the output buffer. However, fseek is required to write the buffer to file.

In the case of both C and POSIX, a conforming implementation seems free to discard the write buffer when fsetpos is called, and C seems to allow fseek to do the same. My first question is whether I've missed something relevant in the standards. The implication here is that a portable application must call fflush (or fseek/rewind in the case of POSIX) to ensure buffered output is actually written before switching from output to input.

Obviously, discarding the write buffer goes against the intent of all of the write functions, and I'm not aware of any implementation that does this or anything comparably counter-intuitive. I'm also aware of my limited awareness, so my second question is whether there are any conforming implementations that don't ensure the buffered content eventually gets written in the proper place.

For context, the GNU documentation maintains the same requirement for fopen and update mode. As with C and POSIX, fsetpos says nothing about the output buffer, but my testing suggests my version does flush the buffer. However, fseek may either flush the buffer or remember enough about it to ensure its contents eventually get written properly.

TL;DR: Does C or POSIX disallow fsetpos from discarding the write buffer? Are there implementations that do this?

EDIT: Nobody has yet presented credible evidence that either standard prohibits fsetpos from discarding the write buffer. Similarly, nobody has mentioned any implementations that do this. However, this is not mentioned in the list of portability issues in the C standard (Annex J), suggesting it is an oversight and not an obscure portability concern. Furthermore, as mentioned by R.., there is no prohibition preventing completely unrelated functions from discarding buffers.

标签: cposix

解决方案


除了“错误”fsetpos部分中的此评论(两次)之外,我没有看到任何需要刷新的情况:

或者需要刷新流的缓冲区,

这看起来像是 POSIX 中的一个遗漏。请在Austin Group 问题跟踪器中提出澄清请求。


推荐阅读